Cancan Ruby Rails Hash Associated Conditionals

时间:2013-06-28 20:07:52

标签: ruby-on-rails ruby cancan

我试图阻止用户访问不属于他/她的个人资料。我的UserProfile模型链接到我的配置文件模型,并且有一个与user_id相关的列。我的想法是使用cancan和“如果user.id与user_profile中的关联user_id不匹配”则拒绝。我已经尝试在许多不同的组合和排列中执行此操作,并且如果使用与UserProfile相关的id字段,则只能使用cancan来拒绝。

使用下面的代码我可以访问

http://localhost:3000/users/8/profile and http://localhost:3000/users/6/profile 

因此用户有权查看任何用户的“使用UserProfile的show方法”。因此,结果正确获取,但cancan不限制基于当前User.id

的权限
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.has_role? :registered
      can :show, UserProfile, :user_id => user.id 
    end
  end
end

class UserProfile < ActiveRecord::Base
  attr_accessible :DOB, :user_id, :address_city, :address_country, :address_state, :address_street, :address_zip, :avatar, :first_name, :gender, :last_name, :position, :time_zone, :years_played
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :user_profile, :dependent => :destroy
end

路线档案

get    '/users/:user_id/profile/'  =>   "user_profiles#show", :as => :user_profile

UserProfile Controller

class UserProfilesController < ApplicationController

 load_and_authorize_resource
 def show

    #@user = User.accessible_by(current_ability) 
    #@user = User.find(params[:user_id])
    #@profile = @user.user_profile


    @profile = UserProfile.where(:user_id => params[:user_id]).first

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @profile }
    end
  end
end

0 个答案:

没有答案