活动记录:创建实例上的验证失败

时间:2017-12-01 08:03:45

标签: ruby-on-rails ruby activerecord

我正在尝试创建一个comment实例。它返回一个验证错误。

comment has one moderation并包含reportable。因此,您可以执行moderation.reportable并返回comment

我希望在创建新的moderation时创建comment实例。

class Comment < ApplicationRecord
      include Reportable

      after_create :create_moderation

      def create_moderation
        blog = self.blog
        self.create_moderation!(blog: blog)
      end
end


class Moderation < ApplicationRecord
    belongs_to :reportable, foreign_key: "reportable_id", foreign_type: "reportable_type", polymorphic: true
...
end



module Reportable
    extend ActiveSupport::Concern

    included do
      has_one :moderation, as: :reportable, foreign_key: "reportable_id", foreign_type: "reportable_type", class_name: "Moderation"
      has_many :reports, through: :moderation
end
  
    

失败/错误:self.create_moderation!(博客:博客)          ActiveRecord的:: RecordInvalid:         验证失败:必须存在可报告

  

修改

尝试添加:

belongs_to :reportable, foreign_key: "reportable_id", foreign_type: "reportable_type", polymorphic: true, optional: true

并获得:

  
    

的ActiveRecord :: NotNullViolation:            PG :: NotNullViolation:ERROR:“reportable_id”列中的空值违反非空约束            DETAIL:失败行包含(2,1,Comment,null,0,null,2017-12-01 09:02:11.81419,2017-12-01 09:02:11.81419,Blog,unmoderate)。            :INSERT INTO“moderations”(“blog_id”,“reportable_type”,“created_at”,“updated_at”,“blog_type”)VALUES($ 1,$ 2,$ 3,$ 4,$ 5)返回“id”

  

2 个答案:

答案 0 :(得分:1)

结合使用optional: true。如下所示:

belongs_to :reportable, foreign_key: "reportable_id", foreign_type: "reportable_type", polymorphic: true, optional: true

参考this。在{Rails 5>中引入了optional: true

修改

after_create :create_moderation

def create_moderation
  blog = self.blog
  self.create_moderation!(blog: blog)
end

我看到两个方法名称相同,即在评论创建后,调用create_moderation再次调用create_moderation。您可以尝试更改方法的名称吗?

另一种说法

您可以将方法更改为

def create_moderation
  blog = self.blog
  Moderation.create!(blog: blog, reportable: self)
end

def create_moderation
  blog = self.blog
  comment = self
  comment.create_moderation!(blog: blog)
end

你还得到同样的错误吗?

答案 1 :(得分:0)

您可以尝试以下代码:

 =B243/3600