I'm creating a blog where articles can be responses to other articles. Articles can also be part of groups. However articles do not have to be in a group or be a response to another article.
I'm attempting to follow the Rails docs to create articles as self-joined records.
I created user, group and article scaffolds:
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
I'm trying to use allow_nil
in the model validation.
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
However when I run the 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)
I get this error:
ActiveRecord::RecordInvalid: Validation failed: Parent must exist, Group must exist
Is there somewhere else where I should be telling Rails it does not need to validate Group and Parent?