Rails范围用当前用户查找 [英] Rails scope find with current user

查看:96
本文介绍了Rails范围用当前用户查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails 3与Devise进行用户认证。假设我有一个用户模型,启用了Devise,一个产品模型,以及一个用户has_many产品。



在我的产品控制器中,我想要我的find方法由current_user作用域,即。



@product = current_user.products.find(params [:id])



除非该用户是管理员用户,即 current_user.admin?



现在,我在几乎所有的方法中都运行该代码,这似乎很乱:

 如果current_user .admin? 
@product = Product.find(params [:id])
else
@product = current_user.products.find(params [:id])
end

有没有更优雅/标准的方法?

解决方案

如果您在很多控制器中运行此代码,您应该可以使其成为一个过滤器,并在ApplicationController中定义一个方法:

  before_filter:set_product,:except => [:destroy,:index] 

def set_product
@product = current_user.admin? ? Product.find(params [:id]):current_user.products.find(params [:id])
end

我不知道你用来确定用户是否是管理员(角色),但如果您查看 CanCan ,它有一个 accessible_by 范围,接受一个能力(控制用户可以和不能做什么的对象),并根据你自己写的权限返回用户有权访问的记录。这可能是你想要的,但是剥离你的权限系统并替换它可能或可能不可行。


I'm using Rails 3 with Devise for user auth. Let's say I have a User model, with Devise enabled, and a Product model, and that a User has_many Products.

In my Products controller I'd like my find method to be scoped by current_user, ie.

@product = current_user.products.find(params[:id])

unless the user is an admin user, i.e. current_user.admin?

Right now, I'm running that code in almost every method, which seems messy:

if current_user.admin?
  @product = Product.find(params[:id])
else
  @product = current_user.products.find(params[:id])
end

Is there a more elegant/standard way of doing this?

解决方案

If you're running this code in a lot of your controllers, you should probably make it a before filter, and define a method to do that in your ApplicationController:

before_filter :set_product, :except => [:destroy, :index]

def set_product
  @product = current_user.admin? ? Product.find(params[:id]) : current_user.products.find(params[:id]) 
end

I don't know what you use to determine if a user is an admin or not (roles), but if you look into CanCan, it has an accessible_by scope that accepts an ability (an object that controls what users can and can't do) and returns records that user has access to based on permissions you write yourself. That is probably really what you want, but ripping out your permissions system and replacing it may or may not be feasible for you.

这篇关于Rails范围用当前用户查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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