Reputation: 1314
Im trying to create a checkbox table of about 20 "interests" that lets the user select as many as they want. I have a Interest & User model with a HABTM relationship (through a "interests_users"join table).
So:
Note.. Im using the Wicked gem to create a multistep form (<-working great)
Upvotes: 0
Views: 3020
Reputation: 146
<% for interest in Interest.find(:all) %>
<%= check_box_tag "user[interest_ids][]", interest.id, @user.interests.include?(interest) %>
<%= interest.name %>
<% end %>
Upvotes: 1
Reputation: 6433
If you're on Rails >= 3.0, then have a look the db/seeds.rb file. You get to put arbitrary Ruby code in that file, which you run through the Rake task rake db:seed
. You can just put a lot of lines like Interest.create :name => 'World Domination'
.
This one is going to depend on how you set up your form. Going off the information you've given, I'd do something like this:
<%= form_for @user do |f| -%>
<% Interest.all.each do |i| -%>
<div><%= i.name -%> <%= check_box_tag 'user[interests][]', i.id, @user.interests.detect{|ui| ui.name == i.name} -%></div>
<% end -%>
<% end -%>
In your controller you would then be able to just update your user model's attributes. Be sure to make sure you are able to mass-assign your parameters, and also keep in mind a limitation of the HTML spec with regard to unchecked checkboxes (read the part titled, "Gotcha").
EDIT: fixed some grammar-related typos.
Upvotes: 2