0

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:

  1. How do i seed the interests table (just has a name:string attribute) with the names of 20 or so pre set interests?
  2. How do i display these in a ERB form allowing the user to select as many as they like?

Note.. Im using the Wicked gem to create a multistep form (<-working great)

2 Answers 2

2
  1. 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'.

  2. 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.

4
  • I have all of the interests stored in an array.. how would i seed the array so i dont have to do "Interest.create :name => 'World Domination'" 20 times over ...would the following work? Interest.create :name => ["Adevnture sports", "Arts and crafts"......]
    – js111
    May 11, 2012 at 20:47
  • ['Adventure sports', 'Arts and crafts'].each{|i| Interest.create :name => i}
    – juanpaco
    May 12, 2012 at 12:35
  • What does the - do in the closing -%> erb insertions? Apr 25, 2019 at 15:27
  • @SagarPandya It controls whitespace in the generated output. Here's a SO answer with more details: stackoverflow.com/questions/4407862/…
    – juanpaco
    Sep 17, 2019 at 3:44
1
<% for interest in Interest.find(:all) %>
  <%= check_box_tag "user[interest_ids][]", interest.id, @user.interests.include?(interest) %>
  <%= interest.name %>
<% end %>
2
  • I have all of the interests stored in an array.. how would i seed the array so i dont have to do "Interest.create :name => 'World Domination'" 20 times over ...would the following work? Interest.create :name => ["Adevnture sports", "Arts and crafts"......]
    – js111
    May 11, 2012 at 21:05
  • Array.each do |interest_name| Interest.create(:name => interest_name) end
    – galulex
    May 12, 2012 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.