0
votes

I have a polymorphic model and want to have a nested form use this model. I am getting no errors but the form is not displaying the nested field. Here are my models and stripped down form:

Polymorphic Model

class SeoMapping < ActiveRecord::Base
  belongs_to :mappingtable, :polymorphic => true
  attr_accessible :seo_url
  validates :seo_url, :presence => true, :uniqueness => true   
end

Page model using the Polymorphic Model

class Page < ActiveRecord::Base
  has_one :seo_mappings, :as => :mappingtable, :dependent => :destroy
  accepts_nested_attributes_for :seo_mappings 
  attr_accessible :content, :h1, :meta_description, :title, :seo_mappings_attributes
  .........
end

Now stripped down form

<%= form_for(@page) do |f| %>
  <% if @page.errors.any? %>
    .......
  <% end %>

  <div class="field">
    <%= f.fields_for :seo_mappings do |builder| %>
      <%= builder.label :seo_url %><br />
      <%= builder.text_field :seo_url %>
    <% end %>
  </div>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  .........
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I cant see why it does not display the fields_for elements. If I comment out accepts_nested_attributes_for the field then displays. Can you see where I am going wrong ?

TY

1
Possibly a silly question but is this the create or edit action you're talking about? And if it's create, did you call @page.build_seo_mapping or something in the controller? Also (may be unrelated) if you use has_one, usually you want to use a singular noun, so has_one :seo_mapping instead of mappings. - Peter Duijnstee
@Peter - I think you're on the money. @Lee, you need to build that association or nothing will show up. And definitely watch your singular/plural naming. The Rails convention would be has_many :seo_mappings or has_one :seo_mapping. - Tom L
Yea it was the build I needed to create. Could bang my head against a wall!!! Thanks Peter - Lee
Glad to help, should've probably made it an answer so you can close. ;) - Peter Duijnstee

1 Answers

1
votes

Possibly a silly question but is this the create or edit action you're talking about? And if it's create, did you call @page.build_seo_mapping or something in the controller?

Also (may be unrelated) if you use has_one, usually you want to use a singular noun, so has_one :seo_mapping instead of mappings.