I have setup my notifications so after I create a trade it kicks the creations of the notification to sidekiq. Then in the notification model it sends the email in a after_create callback. The problem is that when it triggers the mail, it says sender is not found. It retriggers and eventually sends the email but I want it to send on the first time and I don't get why it's not picking up the sender. It definitely exists in the database.
Here are all the related files and the error.
app/models/trade.rb
class Trade < ActiveRecord::Base
has_many :notifications, as: :notifiable
after_create :notify_receiver, :create_public_activity
def notify_receiver
Notification.delay.create(notifiable_id: id, notifiable_type: self.class.name, key: 'initiate_trade', user_id: receiver.user_id)
end
end
app/models/notifications.rb
class Notification < ActiveRecord::Base
belongs_to :notifiable, polymorphic: true
belongs_to :user
after_create :send_email
def send_email
case key
when 'initiate_trade'
NotificationMailer.initiate_trade(self).deliver_now
end
end
end
app/views/notification_mailer/initiate_trade.html.haml
= "#{@notification.notifiable.sender.player.full_name} "
wants to trade
= " #{@notification.notifiable.offered_player_league_countries.joins(:country).select("countries.name").map {|c| c.name}.join(', ')} "
for
= " #{@notification.notifiable.requested_player_league_countries.joins(:country).select("countries.name").map {|c| c.name}.join(', ')}."
Would this help?
I'd guess that after_create hook does not automatically reload record, and thus notifiable is still
nil
in that phase. Sayingreload
before creating the job should fix the issue, right?