class Comment < ActiveRecord::Base belongs_to :post belongs_to :user, optional: true validates_presence_of :date validates_format_of :email, with: /@/ validates_presence_of :body validate :user_or_guest private def user_or_guest user.present? or (author.present? and email.present?) end end class CreateCommentTable < ActiveRecord::Migration[6.0] def change create_table :comments do |t| t.references :post, foreign_key: true, index: true, null: false t.references :user, foreign_key: true t.string :author t.string :email t.string :body, null: false t.timestamps end end end