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)

js111
  • 1,304
  • 4
  • 30
  • 57

2 Answers2

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.

juanpaco
  • 6,303
  • 2
  • 29
  • 22
  • 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 '12 at 20:47
  • `['Adventure sports', 'Arts and crafts'].each{|i| Interest.create :name => i}` – juanpaco May 12 '12 at 12:35
  • What does the `-` do in the closing `-%>` erb insertions? – Sagar Pandya Apr 25 '19 at 15:27
  • @SagarPandya It controls whitespace in the generated output. Here's a SO answer with more details: https://stackoverflow.com/questions/4407862/minus-sign-at-the-end-of-a-erb-sequence – juanpaco Sep 17 '19 at 03:44
1
<% for interest in Interest.find(:all) %>
  <%= check_box_tag "user[interest_ids][]", interest.id, @user.interests.include?(interest) %>
  <%= interest.name %>
<% end %>
galulex
  • 146
  • 3
  • 12
  • 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 '12 at 21:05
  • Array.each do |interest_name| Interest.create(:name => interest_name) end – galulex May 12 '12 at 21:21