Super Spread Sheet S³

Or little computing tricks and hacks

Rails: Choosing and assigning in a HABTM association

Now that I have an HABTM association, I need to provide the user with an interface to choose different categories for an article. (To see how I created the association, see this post.)

Because we have in each of the model files the line stating the association:

# app/models/category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :articles


# app/models/article.rb
class Article < ActiveRecord::Base
  has_and_belongs_to_many :categories

this generates the method:


which returns an array of the category ids which the article object belongs to. Reciprocally the method


returns an array of the article ids in that category object.

To choose a category, in the new.html.erb and edit.html.erb files I included the following (I apologize for the lack of the closing %>, but when I include them, the pre environment just disappears the line):

<% Category.all.each do |cat|
  <% check_box_tag "category_ids[]",, @article.categories.include?(cat)
<% end 

the first argument to check_box_tag is the name of the check box and the [] are very important to indicate that it is an array being passed. The second argument is the value, and the third is a boolean indicating whether the box should be ticked or not.

When the article is updated, the method category_ids updates the categories of the article using the array that was passed in the params hash. The category_ids method was generated by the has_and_belongs_to_many in the Article model.

In the controller, I included the following line as well

    @article.category_ids = params[:category_ids] ||= [8]

where 8 is a default value if nothing is given. If this line was not included no changes are made. This is in disagreement with the code in Bates’ Railscast, which is where I took the inspiration from. (I seem to recall a change in the params hash structure but I am uncertain.) I opted for the change by looking Rails API dock.


One response to “Rails: Choosing and assigning in a HABTM association

  1. Pingback: Rails: multiple categories for an article, HABTM association | Super Spread Sheet S³

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: