Re: HABTM and saving data

Alex Ezell
2005-06-15T15:04:25Z

Duane Johnson wrote:

> Did you see Doug Alcorn''s post about HABTM just a few minutes
before
> yours, or did you just subscribe to the list?

I have been subscribed for several days, but I did not receive his post.
I wonder if I am not getting all the messages. I will take a look at the
archive on Gmane and read it.

> The basic idea for saving the association between two HABTM-assocated
> tables is to:
> 1. Clear the association
> 2. Append all of the objects
>
> Something like this:
>
>     article.categories.clear
>     article.categories <<
Category.find(@params[''category''])
>
> The second line can deal with @params[''category''] as a
single id or as
> an array of ids.

This is precisely the bit I didn''t understand. Thanks so much!

When I add this to my controller such as:

def create()
        @article = Article.new(@params[''article''])
        if @article.save
            @article.categories.clear

@article.categories<<Category.find(@params[''category''])
<--- line 22
            flash[''notice''] = ''Article was
successfully posted.''
            redirect_to :action => ''index''
        else
              flash[''notice''] = ''There was a problem
posting your
article. Please try again.''
              render_action ''edit''
        end
    end

I end up with this error:

Couldn''t find Category without an ID
app/controllers/article_controller.rb:22:in `create''

And this SQL statement in the log seems to be the culprit:
SELECT t.*, j.* FROM articles_categories j, categories t WHERE t.id =
j.category_id AND j.article_id = 7

Why does it need to select from articles_categories? Shouldn''t it
select
the category id from "categories" and then insert that and the article
id from "articles" into articles_categories?

Thanks for your time.

--
Alex Ezell