带有has_many的Rails嵌套表单:通过,如何编辑连接模型的属性? [英] Rails nested form with has_many :through, how to edit attributes of join model?

查看:33
本文介绍了带有has_many的Rails嵌套表单:通过,如何编辑连接模型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆