How can you validate the presence of a belongs to association with Rails?

前端 未结 6 1227
夕颜
夕颜 2020-12-28 17:05

Say I have a basic Rails app with a basic one-to-many relationship where each comment belongs to an article:

$ rails blog
$ cd blog
$ script/generate model a         


        
6条回答
  •  盖世英雄少女心
    2020-12-28 17:56

    I've also been investigating this topic and here is my summary:

    The root cause why this doesn't work OOTB (at least when using validates_presence_of :article and not validates_presence_of :article_id) is the fact that rails doesn't use an identity map internally and therefore will not by itself know that article.comments[x].article == article

    I have found three workarounds to make it work with a little effort:

    1. Save the article before creating the comments (rails will automatically pass the article id that was generated during the save to each newly created comments; see Nicholas Hubbard's response)
    2. Explicitly set the article on the comment after creating it (see W. Andrew Loe III's response)
    3. Use inverse_of:
      class Article < ActiveRecord::Base
        has_many :comments, :inverse_of => :article
      end

    This last solution was bot yet mentioned in this article but seems to be rails' quick fix solution for the lack of an identity map. It also looks the least intrusive one of the three to me.

提交回复
热议问题