用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
...并在topic/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自动创建链接器,这很棒. 现在是我的问题: 我的Linker模型还具有我希望能够通过新主题"表单进行更改的属性.但是,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屋!