HABTM and saving data

Alex Ezell
2005-06-15T13:03:23Z

Hi, all! First-time poster, be gentle.

OK, I am doing a very simple application with articles and categories
only. I have the requisite models as so:

class Article < ActiveRecord::Base
    has_and_belongs_to_many :categories
end

class Category < ActiveRecord::Base
    has_and_belongs_to_many :articles
end

and I also have the corresponding DB tables which are named:
articles
categories
articles_categories

I am able to create and edit and retrieve articles and categories just
fine. What is eluding me is the ability to create the HABTM
relationships and update them from the views. That is, I can display the
categories as checkboxes when adding a new article or editing an
article. However, I do not understand how to take the values of which
categories the user has chosen and insert them into the appropriate
place in my ''create'' action and thusly update them in the
''update'' action.

The checkboxes that I have look like this in the view:
<% @categories.each do |cat| %>
    <input type="checkbox" id="<%= cat.name %>"
name="categories[]"
value="<%= cat.id %>" />
    <%= cat.name %>
<% end %>

And the parameters returned when submitting the form are something like
this:
{"article"=>{"body"=>"Category testing is
fun.", "title"=>"Wow, the 4th
Article", "author"=>"Me"},
"categories"=>["3", "4"]}

So, I know that I am just totally missing this conceptually. In
addition, in the edit view I would need to find out which categories are
associated with a particular article and fill those checkboxes on display.

I have looked at several online tutorials and such, but none of them
seem to really show this though it seems very basic to the whole Rails
construct. Once I get it all working, I should probably type it up for
the wiki as it seems like an area that is underserviced.

Thanks for any assistance you can provide.

--
Alex Ezell