Ruby on rails 如果在操作属性集失败之前,Rails将提前返回
我想在点击任何控制器方法之前,使用传入请求的Ruby on rails 如果在操作属性集失败之前,Rails将提前返回,ruby-on-rails,Ruby On Rails,我想在点击任何控制器方法之前,使用传入请求的remote\u ip执行db查找,以设置特定的控制器类属性。但是,如果查找失败(如果没有对象链接到请求IP),我希望立即返回404响应 例如: class Controller < ApplicationController before_action :set_instance_or_404 def index # do something with @instance end private
remote\u ip
执行db查找,以设置特定的控制器类属性。但是,如果查找失败(如果没有对象链接到请求IP),我希望立即返回404
响应
例如:
class Controller < ApplicationController
before_action :set_instance_or_404
def index
# do something with @instance
end
private
def set_instance_or_404
@instance = Model.find_by(ip_address: request.remote_ip)
# or if no instance is found, immediately return a 404 without hitting "index" method (or any other method for that matter)
end
end
类控制器
任何帮助都将不胜感激 您可以引发
ActiveRecord::RecordNotFound
异常,该异常将停止操作并返回404。或者您可以渲染
或重定向
,这也将停止操作。见文件。下面是每种方法的示例
class Controller < ApplicationController
before_action :set_instance_or_404
def index
# do something with @instance
end
private
def set_instance_or_404
@instance = Model.find_by(ip_address: request.remote_ip)
raise ActiveRecord::RecordNotFound unless @instance # returns 404
end
end
class Controller < ApplicationController
before_action :set_instance_or_404
def index
# do something with @instance
end
private
def set_instance_or_404
@instance = Model.find_by(ip_address: request.remote_ip)
render(status: 404, inline: "Instance not found") unless @instance
end
end
类控制器
Bill Doughty你是个传奇人物!非常感谢您提醒我,我不得不更改您的逻辑,除非将条件放在最后,而不是开始。例如:raiseactiverecord::RecordNotFound除非@instance
Ah,很好,我会更新答案。我正在从内存中进行后台处理,现在忘记了单行Ruby条件语句。谢谢