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

前端 未结 6 1228
夕颜
夕颜 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 18:03

    You are correct. The article needs an id before this validation will work. One way around this is the save the article, like so:

    >> article = Article.new
    => #
    >> article.save! => true >> article.comments.build => # >> article.save! => true

    If you are creating a new article with a comment in one method or action then I would recommend creating the article and saving it, then creating the comment, but wrapping the entire thing inside of a Article.transaction block so that you don't end up with any extra articles.

提交回复
热议问题