2012-09-13 55 views
0

帮我解决这个问题:的Rails的before_filter

我有两个色器件模型(用户和管理员)

和我有一些岗位模型和控制器的路线:

/posts 
/posts/80 
/posts/80/edit 

,我想即: 管理员拥有所有访问 用户可以访问:

/post 
    and 
/post/80 (if he is creator of this post) 

我做到了这一点:

class PostsController < ApplicationController 
     before_filter :check_guest_logged_in!, :except => [:index, :show] 

. 
. 
. 
    private 

    def check_guest_logged_in! 
     if user_signed_in? 
     authenticate_user! 

     elsif admin_signed_in? 
     authenticate_admin! 
     else 
     redirect_to root_path 
     end 
    end 

但在这种情况下,如果用户是授权他可以把浏览器

/posts/80/edit 

,他获得的访问(即使他不是这个职位的创造者)

我怎样才能解决这一问题?

我想类似的东西 私人

def check_guest_logged_in! 
     if user_signed_in? 
     authenticate_user! 

    if (current_user.id == @post.user.id) 
    else 
     return false; 
    end  

     elsif admin_signed_in? 
     authenticate_admin! 
     else 
     redirect_to root_path 
     end 
    end 

,但它不是工作

回答

3

我的建议是使用康康舞宝石

https://github.com/ryanb/cancan

这里有一个很好的railscast上它

http://railscasts.com/episodes/192-authorization-with-cancan

随着康康舞,你可以做这样的事情

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user (not logged in) 
    if user.admin? 
     can :manage, :all 
    else 
     can :read, :all 
    end 
    end 
end 
+0

用了可以可以,我可以这样做呢? –

+1

与您的代码最根本的问题是,你如果用户登录只检查,而不是他们是否是这一职位的所有者。你会在你的职位表中需要一个ACCOUNT_ID列,你可以简单地做一个过滤器前,并检查CURRENT_USER相同的职位所有者,但康康舞确实是一个更好的选择,因为它很容易配置,并保持你的代码DRY –

相关问题