Rails Action Mailer与sidekiq在第一次调用时未在模板中找到关联

时间:2015-06-21 15:13:21

标签: ruby-on-rails ruby actionmailer sidekiq

我已经设置了我的通知,所以在我创建交易后,它将通知的创建提交给sidekiq。然后在通知模型中,它在after_create回调中发送电子邮件。问题是,当它触发邮件时,它表示找不到发件人。它重新触发并最终发送电子邮件,但我希望它第一次发送,我不明白为什么它不接收发件人。它肯定存在于数据库中。

以下是所有相关文件和错误。

应用程序/模型/ 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

应用程序/模型/ 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

应用程序/视图/ 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(', ')}."

enter image description here

1 个答案:

答案 0 :(得分:0)

这会有帮助吗?

def notify_receiver
  reload
  Notification.delay.create(notifiable_id: id, notifiable_type: self.class.name, key: 'initiate_trade', user_id: receiver.user_id)
end

我猜想after_create hook不会自动重新加载记录,因此在该阶段仍然需要nil。在创建作业之前说reload 应该解决这个问题吧?