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

I have a rails app with articles and an authoring model. If I have an author and a position, and you want to indicate that the author should be the owner of the article or that the article belongs to the author, then what is the best practice? In particular:

Does it matter if I set

my_article.author_id = author_one.id 

or if i do

 author_one << my_article 

Associations Used

  • Author has_many article
  • Articles owned by

And by the way, what would be the best way to find this if similar questions arise?

+8
ruby ruby-on-rails activerecord
source share
4 answers

There is no difference between the following three words:

 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 establish the owner of a particular message, the most common and understandable way would be:

 post.author = author post.save 

OR shorter version :

 post.update_attributes(author_id: author.id) # call an implicit save 
+13
source share

I assume that you mean author_one.articles << my_article , not just author_one << my_article

One of the differences between them is that

 author_one.articles << my_article 

Save changes to the database immediately. that is, it will either create an entry for my_article if it has not been saved before, or update an existing entry to have author_id = author_one.id

then

 my_article.author = author_one 

or

 my_article.author_id = author_one.id 

will not persist until you execute my_article.save

+3
source share

Best used:

 has_and_belongs_to_many 

Because the author may have written many articles and articles, may have many authors.

0
source share

IMHO, the right way to do this is to create an instance method in your Article class, for example:

 class Author < ActiveRecord::Base ... def add_an_article(article) unless self.articles.include?(article) self.articles << article end end end 

This will provide better semantics for your model and encapsulate the association manipulation logic ...

That way, your class will also follow the Tell-don't-ask principle: http://pragprog.com/articles/tell-dont-ask .

Unfortunately, most of the Rails community ignores the good OO principles and prefers the easiest but not the right way to do something!

0
source share

All Articles