ruby-on-rails - 如何在 HABTM Rails Association 中创建记录 How make this?

标签 ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

我在我的 has_and_belongs_to_many 模型中创建新关系时遇到了一些问题。我这样定义模型:

journals model

  has_and_belongs_to_many :posts

post model

  has_and_belongs_to_many :journal

我不知道如何创建关联,我做了一个按钮,但我不知道它是如何工作的。我创建了操作 add_post

  def add_post
    @journal_post = JournalsPosts.new
  end

我创建此链接是为了创建关联,但我不知道我现在必须做什么:

<%= link_to "Add to Journal",:controller => "journals",:action => "add_post" %>

重定向工作正常,但我现在不知道如何继续?你知道 HABTM 协会的一些指南吗?我已经试过了 this , 但它没有帮助。

最佳答案

自己研究了一下,应该可以的

def add_post
    j = Journal.first # or find_by, etc
    p = Post.first # or find_by, etc
    j.posts << p # creates a record in journals_posts table
    j.save!
end

(1) 接受的答案听起来好像只能直接建立关联。如果您使用 habtm 关联,您也不会有“JournalsPosts”类,因为它特别避免为中间表使用模型。

(2) 请注意,此关联不会是唯一的。如果您多次调用此方法,您将在 journals_posts 表中获得多个具有相同的两个整数对的条目。

关于ruby-on-rails - 如何在 HABTM Rails Association 中创建记录 How make this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14416872/

相关文章:

ruby-on-rails - 如何强制我的插件随每个请求重新加载?

ruby-on-rails - 多模型保存,如何包装交易和报告错误

javascript - 轨道 3 : submit_tag does not :confirm (while link_to does)

javascript - 使用远程 : true from . js 文件

ruby-on-rails - 无法摆脱 Rails 警告 : "multiple values for a block parameter (0 for 1)"

ruby - Rails, ruby​​ : does SecureRandom. urlsafe_base64 是否需要检查 token 的唯一性?

c# - 通过 COM 从 Ruby 调用 C# .dll

ruby-on-rails - ruby rails : How to sort a collection_select

Jquery AJAX : How to display the Flash error message when validation on the server side fails?

ruby-on-rails - rails 应用程序中的 therubyracer 或 libv8 是什么?