【问题标题】:Undefined method render in Rails controller - Trying to respond to Sendgrid with a 200 status codeRails 控制器中未定义的方法渲染 - 尝试使用 200 状态码响应 Sendgrid
【发布时间】:2014-11-26 23:42:30
【问题描述】:

我正在使用 Sendgrid Parse API 和 Griddler gem 来接收传入的电子邮件。在大多数情况下,这很好用。但是,如果您没有以状态码 200 响应 Sendgrid,他们将假定应用程序没有正确接收 POST 请求并继续尝试进行 POST 3 天。我正在尝试使用状态代码进行响应,但遇到了问题。

在常规 RESTful 路由中,您可以执行类似...

render :status => 200

但是,我相信这必须在控制器中完成才能识别渲染方法。 Griddler 建议您创建一个 EmailProcessor 模型并使用“处理”方法来处理电子邮件。

据我了解,您不能在模型中使用渲染方法。因此,我创建了一个带有类方法的 EmailProcessorsController 类,如下所示。

class EmailProcessor < ActiveRecord::Base

  include ApplicationHelper

  def initialize(email)
    @email = email
    @to = email.to # this is an array
    @from = email.from
  end

  def process
    # do other stuff
    EmailProcessorsController.render_ok
  end
end 

class EmailProcessorsController < ActionController::Base

  def self.render_ok
    render :status => 200
  end
end

以下是我从我的应用程序中得到的错误。它不喜欢渲染方法:(

NoMethodError (undefined method `render' for EmailProcessorsController:Class):
  app/controllers/email_processors_controller.rb:6:in `render_ok'
  app/models/email_processor.rb:16:in `process'

我是一个较新的开发人员,这可能非常简单,但我被困住了。非常感谢有关该问题以及设计的任何想法和方法。谢谢!

更新!

根据@meagar 的建议,我将渲染调用移至控制器,如下所示,但现在我得到一个不同的错误,我不知道该怎么做。

class EmailProcessorsController < ApplicationController

  def initialize(email)
    @email = email
    @to = email.to # this is an array
    @from = email.from
  end

  def process
    # do other stuff
    render :status => 200
  end
end 

没有渲染调用,我不会收到错误消息。这是我调用渲染时遇到的错误...

Module::DelegationError (ActionController::RackDelegation#status= delegated to @_response.status=, but @_response is nil: #<EmailProcessorsController:0x000001063b1558 @email=#<Griddler::Email:0x00000106378ac8 @params={"headers"=>"Received: by mx-007.sjc1.send

【问题讨论】:

  • 您是否尝试过从ApplicationController 继承EmailProcessorsController 而不是ActionController::Base
  • 实际上,从头开始。看起来render 是在ActionController::Instrumentation 中定义的。尝试从中继承。见api.rubyonrails.org/classes/ActionController/…
  • 我说的是ActionController::Instrumentation吗?我的意思是AbstractController::Rendering。不要听我的——我真的不明白 Rails 从哪里得到render
  • 我是从 ActionController::Base 继承的,因为这是 ApplicationController 继承的,而从 ApplicationController 继承是行不通的。这是在黑暗中的一次失败。
  • 更新 - 正确使用 Griddler 时,如果它收到电子邮件,您不必回复 ok 或 200 状态。 Griddler 似乎可以为您执行此操作。

标签: ruby-on-rails ruby model-view-controller sendgrid griddler


【解决方案1】:

render 是实例方法,而不是类方法。你需要实例化你的控制器的一个实例,但这无论如何都行不通。

尝试从您的模型进行渲染是一个严重的错误。该模型不知道涉及到一个 HTTP 请求。您的控制器应该正在创建您的模型,对其调用任何操作,等待成功,然后您的 控制器 应该呈现响应。您尝试做的事情从根本上被破坏了。

【讨论】:

  • 这是有道理的@meagar。我不确定为什么 Sendgrid 和 Thoughtbot 的人(他们都写了关于集成 Thoughtbot 的 griddler gem 来处理传入电子邮件的文章)建议使用处理电子邮件的 EmailProcessor 模型类。让 griddler 调用控制器动作似乎更有意义。
猜你喜欢
  • 1970-01-01
  • 2017-10-31
  • 2016-02-01
  • 1970-01-01
  • 2020-03-24
  • 2016-07-28
  • 2011-04-28
  • 2014-10-21
  • 1970-01-01
相关资源
最近更新 更多