亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Rails嵌套表單與has_many:through,如何編輯連接模型的屬性?

Rails嵌套表單與has_many:through,如何編輯連接模型的屬性?

元芳怎么了 2019-08-15 14:54:47
Rails嵌套表單與has_many:through,如何編輯連接模型的屬性?使用accepts_nested_attributes_for時如何編輯連接模型的屬性?我有3個模型:由連接器加入的主題和文章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所以當我在主題控制器的“新”動作中構建文章時[email protected]...并在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值。如何將其他鏈接器屬性的字段放入“新主題”表單中,這樣它們就不會出現?
查看完整描述

3 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

想出答案。訣竅是:

@topic.linkers.build.build_article

構建鏈接器,然后為每個鏈接器構建文章。因此,在模型中:
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...


查看完整回答
反對 回復 2019-08-15
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

當Rails生成的表單提交給Rails時controller#actionparams將具有與此類似的結構(添加了一些組成的屬性):

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實際上如何Hash使用String鍵進行零索引,而不是Array?嗯,這是因為發送到服務器的表單字段鍵如下所示:

topic[name]topic[linkers_attributes][0][is_active]topic[linkers_attributes][0][article_attributes][title]

創建記錄現在很簡單:

TopicController < ApplicationController
  def create    @topic = Topic.create!(params[:topic])
  endend


查看完整回答
反對 回復 2019-08-15
  • 3 回答
  • 0 關注
  • 870 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號