Form with nested attributes with a has_one association not working in Rails 3

放肆的年华 提交于 2019-12-03 12:38:41

问题


I'm tring to set values for two models that have a has_one association using accepts_nested_attributes_for, but nothing in the fields_for is being shown on the view.

I have confirmed the same code works on Rails 2.x, and it works fine when its a has_many. Code below.

Model

class Parent < ActiveRecord::Base

  has_one :child
  accepts_nested_attributes_for :child
end

class Child < ActiveRecord::Base

  belongs_to :parent
end

Controller

def new
    @parent = Parent.new
    @parent.build_child
end

View

<%= form_for @parent do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>

  <% f.fields_for :child do |builder| %>

    <%= builder.label :childname %>
    <%= builder.text_field :childname %>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

..And after copying that and looking at it, that's a horrible class name.


回答1:


In rails 3 you should use (notice the equal sign in <%=):

<%= f.fields_for [...]

instead of :

<% f.fields_for

same goes with form_for



来源:https://stackoverflow.com/questions/4087742/form-with-nested-attributes-with-a-has-one-association-not-working-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!