简体   繁体   English

从Rails中的ActiveRecord :: RecordNotFound救援

[英]rescue from ActiveRecord::RecordNotFound in Rails

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? 但它不起作用,任何想法我做错了什么?

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. 如果你想使用rescue语句,你需要以一种引发异常的方式使用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

You can also use ActionController 's rescue_from method. 您还可以使用ActionControllerrescue_from方法。 To do it for the whole application at once! 立刻为整个应用程序做!

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

Turns out you were using rescue and find(:first) incorrectly. 事实证明你正在使用救援并且错误地找到(:第一个)。

find :first returns nil if no record matches the conditions. find:如果没有记录符合条件,则首先返回nil。 It doesn't raise ActiveRecord::RecordNotFound 它不会引发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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM