Or little computing tricks and hacks
Rails: Choosing and assigning in a HABTM association
March 5, 2015Posted by on
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 end
# app/models/article.rb class Article < ActiveRecord::Base has_and_belongs_to_many :categories end
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
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", cat.id, @article.categories.include?(cat) <% cat.name <% 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] ||= 
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.