ActiveRecord::RecordInvalid:验证失败:通知者不能为空

ActiveRecord::RecordInvalid: Validation failed: Notified by can't be blank

我在 google 上经常看到这个错误,但我的情况有点不同。我正在使用 delayed_job 并且在运行时出现错误。 notified_byuser 都是两个独立的用户。现在验证错误出现在 notified_by。我在 notified_by 的通知控制器中创建了一个 belongs_to。

我的delayed_job模特check_expired.rb

class CheckExpired < Struct.new(:agreement_id)

    def perform

        agreement = Agreement.find(agreement_id)

        if agreement.accepted == false

            agreement.update_attributes expired: true
            create_notification_expired agreement
        end


    end



    def create_notification_expired(agreement)  

   puts "method was called"
   puts "#{agreement.reviser_user_id}"
    Notification.create!(user_id: agreement.user_id,
                        notified_by_id: agreement.reviser_user_id,
                        agreement_id: agreement.id,
                        notified_by: agreement.reviser_user,
                        description: "Your agreement has expired you have not been charged",
                        identifier: agreement.id,
                        notice_type: 'expired')



    end 


end

我的通知模型

class Notification < ActiveRecord::Base
  belongs_to :notified_by, class_name: 'User'  
  belongs_to :user


  belongs_to :reservation
  belongs_to :offer
  belongs_to :agreement


  validates :user_id, :notified_by_id, :identifier, :notice_type, presence: true

end

总而言之,notified_by 显示验证错误。

'Notification.create!' 方法仅接受模型属性及其值。 'notified_by' 不是 Notification 的属性,而是一个关联。去掉这一行,'Notification.create!'里面的'notified_by: agreement.reviser_user',错误可能会消失。

也有可能'agreement.reviser_user_id'为nil,另一种可能出错。

正在使用此行 'notified_by_id: agreement.reviser_user_id' 将通知对象链接到用户,因此不需要这样做,'notified_by: agreement.reviser_user'