Search code examples
ruby-on-railsrubyactiverecordmodeldelayed-job

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


I see this error a lot on google, but my case is a little different. Im using delayed_job and Im getting an error when it runs. notified_by and user are both two separate users. Now the validation error is on notified_by. I made a belongs_to in the notification controller for notified_by.

my delayed_job model 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

My notification model

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

all in all, notified_by is showing validation error.


Solution

  • 'Notification.create!' method takes in only model attributes and its values. 'notified_by' is not an attribute of Notification, instead it is an association. Remove this line, 'notified_by: agreement.reviser_user' inside of 'Notification.create!', the error may disappear.

    It is also possible 'agreement.reviser_user_id' is nil, another possibility for an error.

    notification object is being linked to user using this line 'notified_by_id: agreement.reviser_user_id', so no need for this, 'notified_by: agreement.reviser_user'