Ruby-on-rails 从 Rails 中的 ActiveRecord::RecordNotFound 救援

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2336593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:20:07  来源:igfitidea点击:

rescue from ActiveRecord::RecordNotFound in Rails

ruby-on-railsactiverecord

提问by Adnan

A user can only edit its own post, so I use the following to check if a user can enter the edit form:

用户只能编辑自己的帖子,因此我使用以下内容来检查用户是否可以输入编辑表单:

  def edit
    @post = Load.find(:first, :conditions => { :user_id => session[:user_id], :id => params[:id]})
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "Wrong post it"
    redirect_to :action => 'index'
  end

But it is not working, any ideas what I am doing wrong?

但它不起作用,任何想法我做错了什么?

回答by Simone Carletti

If you want to use the rescue statement you need to use find()in a way it raises exceptions, that is, passing the id you want to find.

如果要使用救援语句,则需要以find()引发异常的方式使用,即传递要查找的 id。

def edit
  @post = Load.scoped_by_user_id(session[:user_id]).find(params[:id])
rescue ActiveRecord::RecordNotFound
  flash[:notice] = "Wrong post it"
  redirect_to :action => 'index'
end

回答by Tim Baas

You can also use ActionController's rescue_frommethod. To do it for the whole application at once!

您也可以使用ActionControllerrescue_from方法。一次为整个应用程序做这件事!

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  def record_not_found
    render 'record_not_found' # Assuming you have a template named 'record_not_found'
  end
end

回答by EmFi

Turns out you were using rescue and find(:first) incorrectly.

原来你错误地使用了rescue和find(:first)。

find :first returns nil if no record matches the conditions. It doesn't raise ActiveRecord::RecordNotFound

find :first 如果没有符合条件的记录返回 nil。它不会引发 ActiveRecord::RecordNotFound

try

尝试

def edit
  @post = Load.find(:first, :conditions => { :user_id => session[:user_id], :id => params[:id]})
  if @post.nil?
    flash[:notice] = "Wrong post it"
    redirect_to :action => 'index'
  end
end