js111
js111

Reputation: 1314

How to create a rails checkbox form?

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)

Upvotes: 0

Views: 3020

Answers (2)

galulex
galulex

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

juanpaco
juanpaco

Reputation: 6433

  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.

Upvotes: 2

Related Questions