带有 has_many 的 Rails 嵌套表单:通过,如何编辑连接模型的属性? [英] Rails nested form with has_many :through, how to edit attributes of join model?
问题描述
在使用 accepts_nested_attributes_for 时如何编辑连接模型的属性?
How do you edit the attributes of a join model when using accepts_nested_attributes_for?
我有 3 个模型:由链接器加入的主题和文章
I have 3 models: Topics and Articles joined by Linkers
class Topic < ActiveRecord::Base
has_many :linkers
has_many :articles, :through => :linkers, :foreign_key => :article_id
accepts_nested_attributes_for :articles
end
class Article < ActiveRecord::Base
has_many :linkers
has_many :topics, :through => :linkers, :foreign_key => :topic_id
end
class Linker < ActiveRecord::Base
#this is the join model, has extra attributes like "relevance"
belongs_to :topic
belongs_to :article
end
因此,当我在主题控制器的新"操作中构建文章时...
So when I build the article in the "new" action of the topics controller...
@topic.articles.build
...并在topics/new.html.erb中创建嵌套表单...
...and make the nested form in topics/new.html.erb...
<% form_for(@topic) do |topic_form| %>
...fields...
<% topic_form.fields_for :articles do |article_form| %>
...fields...
...Rails 会自动创建链接器,这很棒.现在我的问题是:我的链接器模型也有我希望能够通过新主题"表单更改的属性.但是 Rails 自动创建的链接器的除 topic_id 和 article_id 之外的所有属性都为 nil 值.如何将其他链接器属性的字段放入新主题"表单中,以便它们不会出现为零?
...Rails automatically creates the linker, which is great. Now for my question: My Linker model also has attributes that I want to be able to change via the "new topic" form. But the linker that Rails automatically creates has nil values for all its attributes except topic_id and article_id. How can I put fields for those other linker attributes into the "new topic" form so they don't come out nil?
推荐答案
想出了答案.诀窍是:
@topic.linkers.build.build_article
构建链接器,然后为每个链接器构建文章.所以,在模型中:
topic.rb 需要 accepts_nested_attributes_for :linkers
linker.rb 需要 accepts_nested_attributes_for :article
That builds the linkers, then builds the article for each linker. So, in the models:
topic.rb needs accepts_nested_attributes_for :linkers
linker.rb needs accepts_nested_attributes_for :article
然后在表格中:
<%= form_for(@topic) do |topic_form| %>
...fields...
<%= topic_form.fields_for :linkers do |linker_form| %>
...linker fields...
<%= linker_form.fields_for :article do |article_form| %>
...article fields...
这篇关于带有 has_many 的 Rails 嵌套表单:通过,如何编辑连接模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!