fields_for for nested attribute returns nothing

﹥>﹥吖頭↗ 提交于 2019-12-11 06:25:52

问题


I'm trying to create a nested model form in Rails 3.0.3. Here are my models:

class Bird < ActiveRecord::Base
  has_one :taxon, :as => :organism
  accepts_nested_attributes_for :taxon
end

class Taxon < ActiveRecord::Base
  belongs_to :organism, :polymorphic => true
end

Here's the controller method:

def new
  @bird = Bird.new
  @bird.build_taxon
end

And here's the form:

New Bird
<% form_for @bird do |f| %>
<p>
    <%= f.label :wingspan %>
    <%= f.text_field :wingspan %>
</p>
<p>
    <%= f.label :body_length %>
    <%= f.text_field :body_length %>
</p>
<% f.fields_for :taxon do |builder| %>
    <%= builder.label :common_name %>
    <%= builder.text_field :common_name %>
    <%= builder.label :genus_name %>
    <%= builder.text_field :genus_name %>
    <%= builder.label :species_name %>
    <%= builder.text_field :species_name %>
<% end %>
<%= f.submit %>
<% end %>

When I run the new method, The fields for taxon don't show up. There's no hint of them in the html source. I've heard that this can happen if the nested model is nil (i.e. if I had forgotten to build it in the controller method), but it's there. I added some conditional code in the view just to make sure.

So, who will make me smack my forehead here? What am I missing?

Thanks!


回答1:


Are you using Rails 3? If so it should be:

<%= form_for @bird do |f| %>

and

<%= f.fields_for :taxon do |builder| %>

Note the equals.



来源:https://stackoverflow.com/questions/4480187/fields-for-for-nested-attribute-returns-nothing

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