abalone
abalone

Reputation: 339

Populating Checkboxes on Rails from DB

I am just starting to learn about Rails (ver. 3), and I am trying to create a user registration form with checkbox options for their interests, which may be 0 or more selections. I generated a User scaffold, and an interest model. I seeded the interests table in Postgresql with data:

                                 Table "public.interests"
   Column   |            Type             |                       Modifiers
------------+--------------------+------------------------------------------------
 id         | integer                     | not null default nextval('interests_id_seq'::regclass)
 interest   | character varying(40)       |
 created_at | timestamp without time zone |
 updated_at | timestamp without time zone |
Indexes:
    "interests_pkey" PRIMARY KEY, btree (id)

The view has:

<div class="form_row">
    <label for="interest_ids[]">Interests:</label>
    <% for interest in Interest.find(:all) do %>
      <br><%= check_box_tag 'interest_ids[]', interest.id,
              @model.interest_ids.include?(interest.id) %>
      <%= interest.name.humanize %>
    <% end %>
</div>

(based on Checkboxes on Rails)

The model interest.rb has:

class Interest < ActiveRecord::Base
   has_and_belongs_to_many :users
end

The users controller users_controller.rb has:

 def new
  @user = User.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @user }
  end
end

When I view the page I get:

undefined method `interest_ids' for nil:NilClass

Can someone tell me what's wrong? Thanks.

Upvotes: 1

Views: 1019

Answers (1)

jasonpgignac
jasonpgignac

Reputation: 2306

Have you seen the Railscast on this? http://railscasts.com/episodes/17-habtm-checkboxes

At first glance, if these checkboxes are part of your use create or edit form, I'd think the tag should be:

<%= check_box_tag 'user[interest_ids][]', interest.id, @model.interest_ids.include?(interest.id)%>

Upvotes: 1

Related Questions