accept_nested_attributes_for与belongs_to一起工作吗?

对于这个基本问题,我得到了各种相互矛盾的信息,对于我现在的问题,答案是非常重要的。 所以,很简单,在Rails 3中,是否允许使用belongs_to_attributes_for与belongs_to关系?

class User < ActiveRecord::Base belongs_to :organization accepts_nested_attributes_for :organization end class Organization < ActiveRecord::Base has_many :users end 

在一个视图中:

 = form_for @user do |f| f.label :name, "Name" f.input :name = f.fields_for :organization do |o| o.label :city, "City" o.input :city f.submit "Submit" 

doc epochwolf在第一行中引用了状态“嵌套属性允许您通过父级保存相关logging的属性”。 (我的重点)。

你可能对这个和这个一样的问题感兴趣。 它描述了两种可能的解决scheme:1)将recens_nested_attributes移动到关系的另一端(在本例中是Organization),或者2)在呈现表单之前使用build方法在用户中构build组织。

我还发现了一个要点,它描述了如果愿意处理一些额外的代码,可以使用与belongs_to关系的accept_nested_attributes的潜在解决scheme 。 这也使用build方法。

对于Rails 4中的belongs_to关联,嵌套属性看起来可以正常工作。它可能已经在早期版本的Rails中进行了更改,但是我在4.0.4中进行了testing,并且按预期工作。

对于Rails 3.2中的belongs_to关联,嵌套模型需要以下两个步骤:

(1)将新的attr_accessible添加到您的子模型(用户模型)。

 accepts_nested_attributes_for :organization attr_accessible :organization_attributes 

(2)将@user.build_organization添加到您的子控制器(用户控制器)以创build列organization

 def new @user = User.new @user.build_organization end 
    Interesting Posts