Search code examples
ruby-on-railsrails-console

Rails Associations: access join table by console (HABTM)


I got what I wanted - has and belongs to many associations, using the simple directives from the Rails Guides. In the console it all works just fine, but I am kind of stuck with the following.

Let's say I have two models Article and Category, which both have the directive has_and_belongs_to_many in their models and corresponding to the articles_categories table in the database. In rails console I can see the association working with statements such as these:

%>   @x = Article.find(1)
%>   @x.categories

This way I have a collection of categories stored inside @x. Wonderful. But I cannot really find a way how I could 'add' through console a new category. Right now, I am using SQL to insert the values into the jointable. I am hoping there is a much smarter, Railsy way to do something like this

%> @x.article.categories.category_id = 1  # id of category
%> @x.article.categories.article_id = 1  # id of article
%> @x.save # and written to the database

I am specifically looking for the way to do this in the rails console - so I actually get the feeling of what is happening instead of code snippets that work and I don't get. I am using Rails 4.1.6


Solution

  • You can simply add to the categories collection and Rails will manage the database relationships.

    > category = Category.find(1)
    > article = Article.find(1)
    > article.categories << category
    > article.save
    

    This will add an articles_categories record with an article_id of 1 and a category_id of 1. And, even better, the objects will know about each other:

    > article.categories.include?(category) # => true
    > category.articles.include?(article) # => true