简体   繁体   English

Rails嵌套形式:f.input和input(f)的区别

[英]Rails nested forms: f.input and input(f) difference

I doing some forms, and tried to made a nested form that way: 我正在做一些表格,并尝试以这种方式制作一个嵌套表格:

<%= form_for(@birth) do |f| %>
    <%= f.text_area(:obs) %>
    <%= f.fields_for :child_attributes do |ff| %>
        <%= text_field(:child_attributes, :earring) %>
    <% end %>
<% end %>

Then, in BirthsController, I can get the nested attributes that way: 然后,在BirthsController中,我可以这样获取嵌套属性:

child = params[:child_attributes]

But, if I change my nested form to: 但是,如果我将嵌套形式更改为:

<%= form_for(@birth) do |f| %>
    <%= f.text_area(:obs) %>
    <%= f.fields_for :child_attributes do |ff| %>
        <%= ff.text_field(:earring) %>
    <% end %>
<% end %>

It does not work. 这是行不通的。 What's exactly the difference between them, and why the second way (that I think is more elegant) do not work? 它们之间到底有什么区别,为什么第二种方法(我认为更优雅)不起作用?

Thanks 谢谢

The text_field method knows nothing about your object @birth , so the name of the field will just be child_attributes , that's why you can access it via params[:child_attributes] , but that's not what you want. text_field方法对您的对象@birth ,因此字段名称仅为child_attributes ,这就是为什么您可以通过params[:child_attributes]访问它的原因,但这不是您想要的。

You should use ff.text_field . 您应该使用ff.text_field Then in your Birth model, add: 然后在您的Birth模型中,添加:

accepts_nested_attributes_for :child_attributes
attr_accessible :child_attributes_attributes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM