Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a has_many/belongs_to relation properly in Rails ActiveRecord?

I have a rails app with articles and author model. If I have an author and a post and want to indicate that the author should be the owner of the article, or that the article belongs to the author, what ist the best practice to do so? In particular:

Does it make a difference if I set

my_article.author_id = author_one.id

or If I do

author_one << my_article

The associations that are used are

  • Author has_many articles
  • Articles belongs_to Author

And, by the way, what would be the best way to look it up if similar questions appear?

like image 539
Yo Ludke Avatar asked Nov 30 '12 16:11

Yo Ludke


2 Answers

There is not difference between the 3 following:

my_article.author_id = author_one.id
my_article.save
# same as
my_article.author = author_one
my_article.save
# same as
author_one.articles << my_article

To set the owner of a particular post, the most common and readable way would be:

post.author = author
post.save

OR shorter version:

post.update_attributes(author_id: author.id) # call an implicit save
like image 141
MrYoshiji Avatar answered Sep 20 '22 21:09

MrYoshiji


I'm assuming you mean author_one.articles << my_article rather than just author_one << my_article

One difference between the two is that

author_one.articles << my_article

will save the change to the database immediately. i.e. it will either create the record for my_article if it has not been saved before or it will update the existing record to have author_id = author_one.id

whereas

my_article.author = author_one

or

my_article.author_id = author_one.id

will not be persisted until you do a my_article.save

like image 43
mikej Avatar answered Sep 19 '22 21:09

mikej