【发布时间】:2016-12-09 22:19:58
【问题描述】:
我正在创建一个博客,其中的文章可以是对其他文章的回应。文章也可以是组的一部分。但是,文章不必在一个组中,也不必是对另一篇文章的回应。
我正在尝试按照 Rails 文档以 self-joined records 创建文章。
我创建了用户、组和文章脚手架:
bin/rails g scaffold user username:string email:string birthday:date
bin/rails g scaffold group name:string user:references
bin/rails g scaffold article user:references parent:references title:string subheading:string body:text pub_date:datetime group:references hidden:boolean prompt:boolean
我正在尝试在模型验证中使用allow_nil。
class Article < ApplicationRecord
belongs_to :user
belongs_to :parent, class_name: "Article"
has_many :replies, class_name: "Article", foreign_key: "parent_id"
belongs_to :group
validates :parent, length: {minimum: 1}, allow_nil: true
validates :group, length: {minimum: 1}, allow_nil: true
end
但是当我运行 db:seed:
user1 = User.create(username: "pete01",email: "pete01@gmail.com",
birthday:"1980-01-30")
article1 = Article.create!(user:user1, parent:nil, title:"My First Article",
subheading:"This is important", body:"The body of my first article",
pub_date:"2015-12-26", group:nil, hidden:false, prompt:false)
我收到此错误:
ActiveRecord::RecordInvalid: Validation failed: Parent must exist, Group must exist
还有什么地方我应该告诉 Rails 它不需要验证 Group 和 Parent 吗?
【问题讨论】:
-
你的验证应该验证什么?
-
理想情况下什么都没有。我想关闭对父级和组的验证。
-
然后删除您对验证的调用
-
我得到了同样的错误,没有任何验证调用。我以为我必须通过
allow_nil才能关闭验证。 -
ApplicationRecord是否添加任何验证?请在 Rails 控制台上运行Article.validators并将结果添加到您的问题中。