为了账号安全,请及时绑定邮箱和手机立即绑定

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所以当我在主题控制器的“新”动作中构建文章时......@topic.articles.build...并在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 关注
  • 788 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信