Rails嵌套表單與has_many:through,如何編輯連接模型的屬性?使用accepts_nested_attributes_for時(shí)如何編輯連接模型的屬性?我有3個(gè)模型:由連接器加入的主題和文章class Topic < ActiveRecord::Base
has_many :linkers
has_many :articles, :through => :linkers, :foreign_key => :article_id
accepts_nested_attributes_for :articlesendclass Article < ActiveRecord::Base
has_many :linkers
has_many :topics, :through => :linkers, :foreign_key => :topic_idendclass Linker < ActiveRecord::Base
#this is the join model, has extra attributes like "relevance"
belongs_to :topic
belongs_to :articleend所以當(dāng)我在主題控制器的“新”動(dòng)作中構(gòu)建文章時(shí)......@topic.articles.build...并在topics / new.html.erb中創(chuàng)建嵌套表單...<% form_for(@topic) do |topic_form| %>
...fields... <% topic_form.fields_for :articles do |article_form| %>
...fields...... Rails自動(dòng)創(chuàng)建鏈接器,這很棒。 現(xiàn)在我的問題是:我的鏈接器模型還具有我希望能夠通過“新主題”表單更改的屬性。但是Rails自動(dòng)創(chuàng)建的鏈接器除了topic_id和article_id之外,其所有屬性都有nil值。如何將其他鏈接器屬性的字段放入“新主題”表單中,這樣它們就不會(huì)出現(xiàn)?
3 回答

桃花長相依
TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
想出答案。訣竅是:
@topic.linkers.build.build_article
構(gòu)建鏈接器,然后為每個(gè)鏈接器構(gòu)建文章。因此,在模型中:
topic.rb需要accepts_nested_attributes_for :linkers
linker.rb需要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...

梵蒂岡之花
TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
當(dāng)Rails生成的表單提交給Rails時(shí)controller#action
,params
將具有與此類似的結(jié)構(gòu)(添加了一些組成的屬性):
params = { "topic" => { "name" => "Ruby on Rails' Nested Attributes", "linkers_attributes" => { "0" => { "is_active" => false, "article_attributes" => { "title" => "Deeply Nested Attributes", "description" => "How Ruby on Rails implements nested attributes." } } } }}
注意linkers_attributes
實(shí)際上如何Hash
使用String
鍵進(jìn)行零索引,而不是Array
?嗯,這是因?yàn)榘l(fā)送到服務(wù)器的表單字段鍵如下所示:
topic[name]topic[linkers_attributes][0][is_active]topic[linkers_attributes][0][article_attributes][title]
創(chuàng)建記錄現(xiàn)在很簡單:
TopicController < ApplicationController def create @topic = Topic.create!(params[:topic]) endend
- 3 回答
- 0 關(guān)注
- 864 瀏覽
添加回答
舉報(bào)
0/150
提交
取消