I am trying to create two objects at the same time, but for some reason my second object’s fields are blank.
The models are:
Users: id, name, last, email, password ...
Locations: address, longitude, latitude.
The relationship so are:
User has_many location
Location belongs_to users
Event controller create method:
def create
@event = current_users.events.build(params[:event])
@location = @event.locations.build(params[:location])
@location.longitude = params[:longitude]
@location.latitude = params[:latitude]
respond_to do |format|
if @location.save
@location.longitude = params[:longitude]
@location.latitude = params[:latitude]
if @location.save
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render json: @event, status: :created, location: @event }
else
format.html { render action: "new" }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
end
end
And the form:
<%= f.hidden_field :latitude %>
<%= f.hidden_field :longitude %>
But when I create my locations I get blank for longitude and latitude, my event_id is filled up though. Would there be a better way to create two objects at the same time?
your two fields are generated using a form builder
f. I suspect they are inside aform_forcall. The consequences of this are that the field names will be nested in a namespace for your model. This means thatparams[<model name>][:longitude]andparams[<model name>][:latitude]should have the content of the fields.You can check your console to see what parameters were received by rails. Alternatively you can print the params hash to the console to inspect it’s content:
p params(somewhere in your action).So in order to get everything working you need to access the right params. (Something like
params[:location][:longitude])