I created a joined table for the models category and products (both created with scaffold). The Product model is this:
class Product < ActiveRecord::Base
belongs_to :category
def category_id
category.id if category
end
def category_id=(id)
self.category = Category.find_by_id(id) unless id.blank?
end
end
and the category model is this:
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
In the form.html.erb I create a dropbox with all the classes for the user to choose from:
<p>
<label for="product_category_id">Category:</label><br />
<%= f.collection_select :category_id, Category.find(:all), :id, :name, :prompt => "Select a Category" %>
</p>
Yet when I take a look at the show of the product:
<p>
<b>Category:</b>
<%= @product.category_id %>
</p>
or the list of the products (index.html.erb):
<td><%= product.category_id %></td>
There’s no category. Just blank. I don’t get it. Is something wrong with the category_id method or the association?
Firstly, you don’t need the explicit
category_idandcategory_id=methods.ActiveRecordwill handle those for you for abelongs_toassociation.Secondly, there seems to be a mismatch between whether you want a
has_and_belongs_to_manyor ahas_many/belongs_toassociation. If you have a join table then you have the former, in which case both sides of the association should be declared withhas_and_belongs_to_many. If you are just using acategory_idon the products table then the other end of your association on Category should behas_many :products.With a join model:
you would define in your
Productclass:Then, because your association is a ‘many’ association, you do not get a
.categorymethod on a product. You do however get acategoriesmethod (plus several more methods – look at the has_many documentation). If you name yourcollection_selectcategory_idsthen it should work as expected. You may also want to add the ‘multiple’ option to the select in order to choose more than one category.