I am trying to create a nested form rails in which will create two model at the same time. The model are has follow:
Model/Events
#Data
attr_accessible :customer_id, :description, :locations_attributes
#Relationship
has_many :locations
accepts_nested_attributes_for :locations, :allow_destroy => true
Model/Locations
#Data
attr_accessible :address, :customer_id, :event_id, :latitude, :longitude
#Relationship
belongs_to :customer
belongs_to :event
The view his like this
<%= form_for(@event) do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<%= f.fields_for :locations do |e| %>
<%= e.hidden_field :longitude %>
<%= e.hidden_field :latitude %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
The controller looks like this
def new
@event = Event.new
@location = Location.new
...
def create
@event = current_customer.events.build(params[:event])
@event.locations.build(params[:locations])
respond_to do |format|
...
The issues is that when I create the events, the form is generated, it create the events and create a locations and associated to the events, but my longitude and latitude field are empty. I must note they are float type, but i don’t understand why it shouldn’t work
Update: I notice for me to be able to access the field_for i must change the field_for to single
<%= f.fields_for :location do |e| %>
But then when doing this i get the following error when trying to create the event
Can't mass-assign protected attributes: location
and the params is has follow
"location"=>{"longitude"=>"-80.9460917",
"latitude"=>"46.4350391"}
This is my javascript
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
document.getElementById('event_location_latitude').value=position.coords.latitude;
document.getElementById('event_location_longitude').value=position.coords.longitude;
}
I admits its ugly but it does the jobs from application.js I called it with a function in the form
<script type="text/javascript">
getLocation();
</script>
Which is just before <% end %> of the form
check this out.
http://railscasts.com/episodes/196-nested-model-form-revised
if you have questions after viewing it. let me know
In your hidden field code you need to set a value. For example.