Reputation: 1934
I am trying to create two object at the same time. The best approach I have is to used fields_for. and the relationship is has_many.
model/location.rb
attr_accessible :address, :customer_id, :event_id, :latitude, :longitude
belongs_to :customer
belongs_to :event
model/event.rb
attr_accessible :locations_attributes
has_many :locations, :dependent => :destroy
accepts_nested_attributes_for :locations
The form is has follow:
<%= form_for(@event) do |f| %>
...
<%= f.fields_for :locations do |e| %>
<%= e.text_field :longitude %>
<%= e.text_field :latitude %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
My fields won't show up, I have followed the documentation has_many from this section http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for and notice if in my f.fields_for :locations change it to singular than the fields will show up but i won't be able to create it because i am not allow to modify the locations_attributes.
UPDATE:
If i singular it. I change this to my event model
attr_accessible :description, :title, :location_attributes
The error is like this
app/controllers/events_controller.rb:60:in `new'
app/controllers/events_controller.rb:60:in `create'
My controller is like this
line 60: @event = Event.new(params[:event])
Upvotes: 1
Views: 174
Reputation: 2091
You should be doing this in your form: (location not locations)
<%= f.fields_for :location do |e| %>
<%= e.text_field :longitude %>
<%= e.text_field :latitude %>
<% end %>
and in your model event.rb
attr_accessible :description, :title, :locations_attributes
(locations not location)
Upvotes: 1