我正在创建一个博客,文章可以回复其他文章.文章也可以是群体的一部分.但是,文章不必属于一个组或是对另一篇文章的回应.
我正在尝试按照Rails文档创建文章作为自联接记录.
我创建了用户,组和文章脚手架:
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?
解决方法是找到该文件new_framework_defaults.rb
,将其更改为false
:
Rails.application.config.active_record.belongs_to_required_by_default = false