第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

元芳怎么了 2019-08-15 14:54:47
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...


查看完整回答
反對(duì) 回復(fù) 2019-08-15
?
梵蒂岡之花

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


查看完整回答
反對(duì) 回復(fù) 2019-08-15
  • 3 回答
  • 0 關(guān)注
  • 864 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)