Forum: Ruby on Rails HABTM & CheckBoxes

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
4b0889adddec0b9bae5435e0c233b1e3?d=identicon&s=25 Davo (Guest)
on 2008-10-13 07:20
(Received via mailing list)
I'm trying to achieve something that I assume is fairly common?

I have a Category table and a Brand Table.
When I create a new Category I want a list of checkboxes to appear,
and when checked they update the category_brand table.

Here are the models.
class Category < ActiveRecord::Base
  has_and_belongs_to_many :brands
class Brand < ActiveRecord::Base
  has_and_belongs_to_many :categories

Here is the view to add a new category.
<h1>Add a new Category</h1>
<% form_for(@category) do |f| %>
  <%= f.error_messages %>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  <h3>Add Brands required for this new category</h3>
  <% for b in @brands do -%>
    <%= check_box_tag "categories[brand_ids][]", "#{}" -%>
    <%= "#{}" -%>
  <% end -%>
    <%= f.submit "Create" %>
<% end %>
<%= link_to 'Back', categories_path %>

I have read all the documentation & tutorials I can find on this and
it is not clear to me if anything has to be done in the controller?
Some examples imply it happens because of the association and other
example have code such as:
 @category.brands = brand.find(@params[:brand_ids]) if
Which produces an error for me..
You have a nil object when you didn't expect it!

TIA - Dave Porter
1b507a552850441a516948d488962d2e?d=identicon&s=25 Sniper Abandon (mokkai)
on 2008-10-13 07:27
Davo wrote:

>  @category.brands = brand.find(@params[:brand_ids]) if @params[:categories][:brand_ids]

check this
1b507a552850441a516948d488962d2e?d=identicon&s=25 Sniper Abandon (mokkai)
on 2008-10-13 07:28
Pokkai Dokkai wrote:
> Davo wrote:
>>  @category.brands = brand.find(@params[:categories][:brand_ids]) if 
> check this
4b0889adddec0b9bae5435e0c233b1e3?d=identicon&s=25 Davo (Guest)
on 2008-10-13 07:52
(Received via mailing list)
All working, no code required in controller
( other than code mentioned in RailsCasts HABTM   )

I had the naming wrong for the brands_categories table !

cheers, Dave

On Oct 13, 1:28 pm, Pokkai Dokkai <>
This topic is locked and can not be replied to.