Ruby on Rails simple_form_for all.each do
I am using Rails 3.0, Ruby 1.9.2 and the Plataformatec simple_form gem. This code works with a form_for but not simple_form_for:
<%= simple_form_for(@provider) do |f| %>
<% Car.all.each do |c| %>
<div>
<%= check_box_tag :car_ids, c.id, @store.cars.include?(c), :name => 'store[car_ids][]' %>
$<%= c.cost %> | <%= c.description %>
</div>
<% end %>
<div class="actions">
<%= f.submit "New" %>
</div>
<% end %>
开发者_如何学Python
How do I get it to work with simple_form_for?
Thanks in advance!
You can't use simple_form
right the same way as form_for
.
For example ther is no any check_box_tag
method in simple_form
gem. There is ONLY inuput
fields that you can specify with :as
option. So your check_box_tag
will be converted to
f.input car_ids, ..., :as => :check_box
Checkout Usage, Rdoc and other useful stuff https://github.com/plataformatec/simple_form
The problem was in the controller code.
In the "new" controller action I can't simply perform:
@provider = Provider.new(params[:provider])
as one would normally.
Instead I have to process each parameter separately:
@provider.location = params[:provider][:location] etc...
For the Car check boxes, I add each car_id from the car_ids parameter to the "has_many" cars model association one at a time:
car_ids = params[:provider][:car_ids]
car_ids.each do |cid|
@provider.cars << Car.find(cid)
end
Then I can call:
@provider.save!
And it saves correctly (my initial problem was that it wasn't saving the selected Cars).
For some reason, I was able to figure this out only after posting the question here. Funny how that works.
Thanks all for your replies!
精彩评论