我在我的 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/