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

时间:2017-06-28 22:38:43

标签: ruby-on-rails ruby activerecord model delayed-job

我在谷歌上看到了很多这个错误,但我的情况有点不同。我正在使用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显示验证错误。

1 个答案:

答案 0 :(得分:1)

&#39; Notification.create&#39!;方法仅接受模型属性及其值。 &#39; notified_by&#39;不是通知的属性,而是一个关联。删除此行,&#39; informed_by:agreement.reviser_user&#39;在&#39; Notification.create!&#39;内,错误可能会消失。

也可以&#39; agreement.reviser_user_id&#39;是零,是错误的另一种可能性。

通知对象正在使用此行&#39; informed_by_id:agreement.reviser_user_id&#39;链接到用户,因此不需要,&#39; informed_by:agreement.reviser_user&#39;