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

前端 未结 4 1052
一整个雨季
一整个雨季 2021-01-12 06:46

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 articl

相关标签:
4条回答
  • 2021-01-12 07:08

    IMHO, the correct way of doing that is creating a instance method on your Article class, like the following:

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

    This will provide a better semantic to your model and encapsulate the logic of the association manipulation...

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

    Unfortunately, most of the Rails community ignores good OO principles and prefer the easiest but not right way of doing something!

    0 讨论(0)
  • 2021-01-12 07:09

    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
    
    0 讨论(0)
  • 2021-01-12 07:20

    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

    0 讨论(0)
  • 2021-01-12 07:24

    Best thing is to use:

    has_and_belongs_to_many
    

    Because, author may have written many article and article can have many authors.

    0 讨论(0)
提交回复
热议问题