在 Rails 中保存三层嵌套表单时出现问题
我有一个三级嵌套表单,但第三个类未保存。
我有三个模型类(简化)
class A
has_one :b
accepts_nested_attributes_for :b
end
和
class B
belongs_to :a
has_many :c
accepts_nested_attributes_for :c
end
控制器
class C
belongs_to :b
end
我的视图(简化)
<%= form_for [@a] do |f| -%>
<%= f.fields_for :b do |b_form| -%>
<%= b_form.fields_for :c do |c_form| -%>
<% end %>
<% end %>
<% end %>
散列
def new
@a= A.new
b = @a.b = B.new
b.c.build
end
def create
if (@a= A.create(params[:a])).valid?
//flash succes
end
end
如下所示: 测试{"a"=>{"title"=>"测试", "body"=>"
", "b_attributes "=>{"title"=>"testt", "c_attributes"=>{"0"=>{"title"=>"testtt"}}}}}
但只有 A和 B 被创建。 C 不是,它不会在我的日志中抛出错误或其他内容。
谢谢!
编辑:
解决方案(感谢Zabba)
在B类
中添加attr_accessible :c_attributes
I've a three level nested form, but the third class is not saved.
I've three model classes (simplified)
class A
has_one :b
accepts_nested_attributes_for :b
end
and
class B
belongs_to :a
has_many :c
accepts_nested_attributes_for :c
end
and
class C
belongs_to :b
end
My view (simplified)
<%= form_for [@a] do |f| -%>
<%= f.fields_for :b do |b_form| -%>
<%= b_form.fields_for :c do |c_form| -%>
<% end %>
<% end %>
<% end %>
The controller
def new
@a= A.new
b = @a.b = B.new
b.c.build
end
def create
if (@a= A.create(params[:a])).valid?
//flash succes
end
end
The hash looks like this:{"a"=>{"title"=>"test", "body"=>"<p>test</p>\r\n<br />", "b_attributes"=>{"title"=>"testt", "c_attributes"=>{"0"=>{"title"=>"testtt"}}}}}
But only A and B are created. C is not, it's not trowing an error or something in my logs..
Thanks!
Edit:
The solution (thanks to Zabba)
add attr_accessible :c_attributes
in class B
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在
class B
中添加attr_accessible :c_attributes
(应该成为答案)
Try adding
attr_accessible :c_attributes
inclass B
(should make into answer)
控制器
The controller