假设我有一个基本的Rails应用程序,其基本的一对多关系,其中每个评论都属于一篇文章:
$ rails blog
$ cd blog
$ script/generate model article name:string
$ script/generate model comment article:belongs_to body:text
Run Code Online (Sandbox Code Playgroud)
现在我添加代码来创建关联,但我也想确保在创建注释时,它总是有一篇文章:
class Article < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :article
validates_presence_of :article_id
end
Run Code Online (Sandbox Code Playgroud)
现在让我们说我想创建一篇带有评论的文章:
$ rake db:migrate
$ script/console
Run Code Online (Sandbox Code Playgroud)
如果你这样做:
>> article = Article.new
=> #<Article id: nil, name: nil, created_at: nil, updated_at: nil>
>> article.comments.build
=> #<Comment id: nil, article_id: nil, body: nil, created_at: nil, updated_at: nil>
>> article.save!
Run Code Online (Sandbox Code Playgroud)
你会收到这个错误:
ActiveRecord::RecordInvalid: Validation failed: Comments is invalid
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为评论还没有page_id. …