Rails Associations: Accessing the Connection Table Using the Console (HABTM)

I got what I wanted - has and belongs to many associations using simple directives from the Rails Guides. Everything works fine in the console, but I'm kind of stuck with the following.

Let's say I have two models Article and Category that have has_and_belongs_to_many directives in their models and correspond to the articles_categories table in the database. In the rails console, I see an association working with statements such as:

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

      

This way I have a set of categories stored inside @x. Wonderful. But I cannot find a way how I could "add" a new category via the console. Right now, I am using SQL to insert values ​​into compliant. I hope 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'm specifically looking for a way to do this in the rails console - so that I really get a feel for what's going on, not the code snippets that work and I don't get it. I am using Rails 4.1.6

+3


source to share


2 answers


You can simply add to a collection categories

and Rails will manage the database relationship.

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

      



This will add an articles_categories entry with article_id of 1 and category_id of 1. Better yet, the objects will know about each other:

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

      

+6


source


Why don't you try:

@article.categories.build (params)

      



where the parameters will contain the attributes for the new category

+1


source







All Articles