我一直在收到关于这个基本问题的各种相互矛盾的信息,答案对我目前的问题非常重要。因此,非常简单,在Rails 3中,允许或不允许将accepts_nested_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"
答案 0 :(得分:22)
从Rails 4开始,嵌套属性似乎适用于belongs_to关联。它可能在早期版本的Rails中已经更改,但我在4.0.4中进行了测试,它确实按预期工作。
答案 1 :(得分:21)
doc epochwolf在第一行中引用了状态“嵌套属性允许您保存相关记录的属性通过父。” (我的重点)。
您可能对this other SO question which is along the same lines as this one感兴趣。它描述了两种可能的解决方案:1)将accepts_nested_attributes移动到关系的另一端(在本例中为Organization),或2)using the build
method以在呈现表单之前在User中构建组织。
如果你愿意处理一些额外的代码,我还找到了一个描述a potential solution for using accepts_nested_attributes with a belongs_to relationship的要点。这也使用build
方法。
答案 2 :(得分:10)
对于Rails 3.2中的belongs_to
关联,嵌套模型需要以下两个步骤:
(1)将新的attr_accessible
添加到您的子模型(用户模型)。
accepts_nested_attributes_for :organization
attr_accessible :organization_attributes
(2)将@user.build_organization
添加到子控制器(用户控制器)以创建列organization
。
def new
@user = User.new
@user.build_organization
end
答案 3 :(得分:4)
For Ruby on Rails 5.2.1
class User < ActiveRecord::Base
belongs_to :organization
accepts_nested_attributes_for :organization
end
class Organization < ActiveRecord::Base
has_many :users
end
Just got to your controller, suppose to be "users_controller.rb":
Class UsersController < ApplicationController
def new
@user = User.new
@user.build_organization
end
end
And the view just as Nick did:
= 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"
At end we see that @user3551164 have already solved, but now (Ruby on Rails 5.2.1) we don't need the attr_accessible :organization_attributes