ruby-on-rails Rails Mailer - undefined method `[]' for nil:NilClass

mrwjdhj3  于 2023-05-08  发布在  Ruby
关注(0)|答案(1)|浏览(200)

我希望在其他用户删除与原始用户相关的对象时向该用户发送电子邮件。但现在我得到了这个错误:突出显示@agreement = params[:agreement]undefined method[]' for nil:NilClass`(在完整代码下方)。基本上,我试图在对象被删除之前发送电子邮件。
我的邮件

def agreement_delete
        @agreement = params[:agreement]
        @sent_user = User.find(@agreement.user_id)
        @user = User.find(@agreement.thought.user_id)
        @user_email = @user.email

        mail(to: @user_email, subject: "It's been deleted!")
    end

我的协议控制器

def destroy
        @agreement = Agreement.find(params[:id])
        UserMailer.with(agreement: @agreement).agreement_delete.deliver_later
        @agreement.destroy
        redirect_back 
    end

我的协议rb

before_destroy :check_delete

  private
  def check_delete
        UserMailer.agreement_delete.deliver
  end

我认为params[:agreement]有什么问题,但是在创建协议时发送电子邮件的邮件程序工作正常,并且具有相同的@agreement = params[:agreement]。我真的很感激帮助。
顺便说一句,电子邮件确实会被发送。只是应用程序由于错误而中断。

1sbrub3j

1sbrub3j1#

您的协议控制器

def destroy
    @agreement = Agreement.find(params[:id])
    # you can't deliver_later, the object will be gone.
    UserMailer.agreement_delete(@agreement).deliver_now
    @agreement.destroy
    redirect_back 
end

你的邮件

def agreement_delete(agreement)
    # bring in the information you need, in this case: an agreement record
    @agreement = agreement
    @sent_user = User.find(@agreement.user_id)
    @user = User.find(@agreement.thought.user_id)
    @user_email = @user.email

    mail(to: @user_email, subject: "It's been deleted!")
end

你的协议rb

before_destroy :check_delete

  private
  def check_delete
    # the email is being sent twice?
    # Once from the controller, and once from the model? Why?
    # UserMailer.agreement_delete(self).deliver
  end

在评论中,你说params[]以某种方式可用于其他邮件。奇怪又出乎意料。你不应该依赖它。为您的方法提供它们需要的信息并且只提供它们需要的信息是一种更好、更安全的做法。
如果你真的想使用.deliver_later,我会建议一个不同的模式:
#destroy操作应该调用可以.perform_later的作业。作业应发送电子邮件,然后删除记录。

相关问题