问题
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