我正在创建一个 API,我希望外部只能访问更新方法来实现报告。但如果没有报告,我想创建它。我知道最简单的方法就是在更新方法中创建它,但是一旦我已经有了一个创建方法构建,我想知道是否可以调用它并向它发送一些参数。
我在这里环顾四周Rails 3: Call functions inside controllers或 API 但我没有找到任何好的解决方案。
谁有更好的?
非常感谢您。
最佳答案
你不应该从另一个 Action 调用你的 Controller 的 Action 。
为什么?因为 Controller 的每一个 Action 都被定义为响应一个请求,它有几个属性(例如 IP、参数、 session 、HTTP header 等)。想象一下,在 Controller 中调用另一个 Action 会有多“奇怪”。
如果您想执行与更新操作无关的“额外逻辑”(例如,创建),您应该调用此 Controller 的 protected (只能通过 Controller 及其子级访问)方法。
在您的情况下,您可以这样做:
class ReportsController < ApplicationController
def update
@report = Report.where(id: params[:report_id]).first
if @report.nil?
create_report(params)
else
# etc.
end
end
protected
def create_report(params)
Report.create(params)
end
end
关于ruby-on-rails - 调用内部 Controller Action 并在它们之间发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18258871/