Reputation: 1554
I have a model that has amenities with a 1:1 relationship:
class Listing < ActiveRecord::Base
attr_accessible :address1, :address2, :bath, :bedroom, :city, :description, :neighborhood, :sleeps, :sqft, :state_id, :title, :zip, :images_attributes, :amenity_attributes
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => true
has_one :amenity
accepts_nested_attributes_for :amenity, :allow_destroy => true
end
And Amenities table:
class Amenity < ActiveRecord::Base
attr_accessible :air_conditioning, :balcony
belongs_to :listing
end
Lastly, my view:
<%= simple_nested_form_for (@listing), :html => {:multipart => true} do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :sleeps %>
<%= f.input :bath %>
<%= f.input :bedroom %>
<%= f.input :sqft %>
<%= f.input :neighborhood %>
<%= f.input :address1 %>
<%= f.input :address2 %>
<%= f.input :city %>
<%= f.input :state_id %>
<%= f.input :zip %>
<%= f.input :description %>
</div>
<!-- amenities -->
<%= f.fields_for :amenities do |a| %>
<div class="amenities">
<label><%= a.check_box :smoking %> Smoking Allowed</label>
</div>
<% end %>
<!-- end amenities -->
<!-- Submit button -->
<% end %>
When I hit submit I get the error:
Can't mass-assign protected attributes: amenities
Any idea what's up here? It won't submit even though I allow :amenities_attributes and accepts_nested tags.
Upvotes: 2
Views: 844
Reputation: 1554
Fixed:
class Listing < ActiveRecord::Base
has_one :amenity
accepts_nested_attributes_for :amenity
after_initialize do
self.amenity ||= self.build_amenity()
end
end
Upvotes: 0
Reputation: 4097
You have a has_one association so amenities should not be plural.
change
<%= f.fields_for :amenity do |a| %>
EDIT
<%= f.fields_for :amenity do |a| %>
<div class="amenities">
<%= a.label :smoking, 'Smoking Allowed' %>
<%= a.check_box :smoking %>
</div>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
Also, checkout this documentation for a one to one association, http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Upvotes: 1