Reputation: 505
I'd like to know how to manipulate the form_for in order to change how the params[] are being sent to my Controller.
I'm posting to the Registration#create controller using this form:
<%= form_for @registration, method: :post do |form| %>
<div class="form form-actions">
<%= form.hidden_field :occurrence_id, :value => @occurrence.id %>
<%= submit_tag "Yes, register", class: 'btn btn-primary' %>
<%= link_to "Cancel", root_path, class: 'btn' %>
</div>
<% end %>
Here is the Registration#create controller:
def create
if params[:occurrence_id]
@occurrence = Occurrence.find(params[:occurrence_id])
@registration = Registration.new(registration_date: Date.today, user: current_user, occurrence: @occurrence)
if @registration.save
flash[:success] = "Course registration saved with success."
else
flash[:error] = "There was a problem saving the registration."
end
redirect_to occurrence_path(@occurrence)
else
flash[:error] = "Occurrence missing"
redirect_to root_path
end
end
Now my params[:occurrence_id] is not being evaluated because the form is sending the hidden field as follows:
{"utf8"=>"✓",
"authenticity_token"=>"5RFiAq3DiqauNzSpnXIcPzWEl9UuGqoXfYAvRiB6GKk=",
"registration"=>{"occurrence_id"=>"2"},
"commit"=>"Yes,
register"}
I'm "expecting" this (with my limited knowledge of RoR)
{"utf8"=>"✓",
"authenticity_token"=>"5RFiAq3DiqauNzSpnXIcPzWEl9UuGqoXfYAvRiB6GKk=",
"occurrence_id"=> "2",
"commit"=>"Yes,
register"}
So how can I change my form so that params[:occurrence_id] is sent and not params[:registration][:occurrence_id]?
Upvotes: 1
Views: 147
Reputation: 14864
Chagne the if params[:occurrence_id]
to if params[:registration][:occurrence_id]
This is how Rails managed to handle properties which belong to a specific object in an html document.
There might be other inputs in the form or multiple objects on a document, this how they will get organized.
If you intentioally want mentioned behaviour then you must use the form_tag
instead of form_for.
Upvotes: 2