Reputation: 225
i have an index view that shows all available classes i want a link to "sign up for class" that redirects me to the "sign up" form and fill up some other values and when the sign up is created it saves the values that i filled up plus the foreign key of the class i just passed via the link to method
classes index:
<h1>Listof classes</h1>
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% @classes.each do |class| %>
<tr>
<td><%= class.id %></td>
<td><%= class.name %></td>
<td><%= class.description %></td>
<td><%= link_to 'sign up!', new_sign_up_path(:class_id => class.id), method: :post %></td>
</tr>
<% end %>
</tbody>
</table>
sign_up controller:
class SignUpsCOntroller < ApplicationController
before_action :set_sign_ups, only: [:show, :edit, :update, :destroy]
# GET /sign_ups/new
def new
@sign_up = SignUp.new
end
def set_sign_ups
@sign_up = SignUp.find(params[:id])
end
def sign_up_params
params.require(:sign_up).permit(:date, :status, :type, :class_id)
end
end
and my sign ups form:
<%= form_for(@sign_up) do |f| %>
<div class="field">
<%= f.label :date %><br>
<%= f.date_select :date %>
</div>
<div class="field">
<%= f.label :status %><br>
<%= f.check_box :status %>
</div>
<div class="field">
<%= f.label :type %><br>
<%= f.number_field :type %>
</div>
<div class="field">
<%= f.hidden_field :class_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
when i save it it doesn't save the the class_id... i've tried parsing it to integer i've tried it without the hidden field but it allways passes it as blank en saving... any ideas?
Upvotes: 1
Views: 1239
Reputation: 34774
You are just passing in params[:class_id]
with your extra parameter on the link_to
. Your form however is for an object with a class_id
attribute so it is expecting your @sign_up
object to have a class_id
attribute.
Basically for your new
action you'll need to set up @sign_up
with the class_id
for it from the parameters:
def new
@sign_up = SignUp.new
@sign_up.class_id = params[:class_id] if params.has_key?(:class_id)
end
This will set the class_id
to the parameter passed in from the link_to
url.
Then your form should work okay because the f.hidden_field
will look at the current value of class_id
on @sign_up
and set that as the value of the input. It doesn't matter that you haven't saved it at this point - the form_for
will use the unsaved state to populate the inputs.
Upvotes: 2