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

前端 未结 4 1084
一整个雨季
一整个雨季 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!

提交回复
热议问题