从ActiveRecord的:: RecordNotFound Rails中救援 [英] rescue from ActiveRecord::RecordNotFound in Rails

查看:193
本文介绍了从ActiveRecord的:: RecordNotFound 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.

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

这篇关于从ActiveRecord的:: RecordNotFound Rails中救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆