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

前端 未结 6 1226
夕颜
夕颜 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:45

    If you're using Rails 2.3 you are using the new nested model stuff. I have noticed the same failures with validates_presence_of as you pointed out, or if :null => false was specified in the migration for that field.

    If your intent is to create nested models, you should add accepts_nested_attributes_for :comments to article.rb. This would allow you to:

    a = Article.new
    a.comments_attributes = [{:body => "test"}]
    a.save!  # creates a new Article and a new Comment with a body of "test"
    

    What you have is the way it should work to me, but I'm seeing that it doesn't with Rails 2.3.2. I debugged a before_create in comment using your code and no article_id is supplied through the build (it is nil) so this is not going to work. You'd need to save the Article first as Nicholas pointed out, or remove validation.

提交回复
热议问题