Rails 3 ActiveAdmin CanCan。如何设置用户应该只看到属于他的记录?

时间:2012-01-20 00:26:13

标签: ruby-on-rails ruby cancan activeadmin

我设置属于客户类的admin_users(客户是公司)。所以客户有很多admin_users。

我正在尝试限制对属于某个客户的货件记录的访问权限。我不希望客户观看其他客户的数据。所以我设置了它,但似乎什么也没做......

班级能力       包括CanCan :: Ability

  def initialize(user)
    user ||= AdminUser.new       
    if user.role == "administrator"
        can :manage, :all
    else
      cannot :create, :all
      cannot :update, :all
      cannot :destroy, :all
      can :read, Shipment do |shipment|
        shipment.customer == user.customer
      end
    end
  end 
end

我确实在shipping.rb中有这个...

ActiveAdmin.register Shipment do
  menu :if => proc{ can?(:read, Shipment) }, :priority => 1
  controller.authorize_resource

  index do
    column "File #", :sortable => :file_number do |shipment|
      link_to shipment.file_number, admin_shipment_path(shipment)
    end
    [... more columns ...]
    default_actions if can? :manage, Shipment
  end

  show :title => :file_number do
  panel "Shipment Details" do
  attributes_table_for shipment do
    row("File number") {shipment.file_number}
    row("Mode") {shipment.mode}
    row("Ocean Rate") { number_to_currency shipment.ocean_rate}
    row("Customer") { link_to shipment.customer.company_name, admin_customer_path(shipment.customer)}
    row("Shipper") { link_to shipment.shipper.company_name, admin_shipper_path(shipment.shipper)}
    row("Broker") { link_to shipment.broker.company_name, admin_broker_path(shipment.broker)}
  end
end

[...more show action stuff...]

因此,在索引页面中,所有货件都会显示,如果我以客户A身份登录并点击客户B的货件,我可以看到它,但它应该阻止我。

更多信息......

shipments_controller.rb
class ShipmentsController < InheritedResources::Base
  before_filter :authenticate_admin_user!
end

4 个答案:

答案 0 :(得分:2)

Active Admin有一个用于处理范围的内置方法。见这里:http://activeadmin.info/docs/2-resource-customization.html#scoping_the_queries

答案 1 :(得分:1)

我的应用中遇到了类似的问题。我有超级用户和管理员,管理员只能在他们的组织中看到其他管理员。

应用程序/模型/ ability.rb

if user.organization_admin?
  can :manage, User, :organization_id => user.organization_id
end

应用程序/管理/ users.rb的

controller do load_and_authorize_resource :except => :index
  def scoped_collection
    end_of_association_chain.accessible_by(current_ability)
  end
end

答案 2 :(得分:0)

我不知道为什么它不起作用,但can? :read, Shipment不会查找can :read, Shipment do |shipment| ...的权限。

要根据此权限进行验证,您必须指定货件的特定实例,例如can :read, @shipment

在调用menu :if => ...行之前,您需要找到一种获取已访问货件实例的方法。


您是否尝试使用controller.load_and_authorize_resource而非authorize_resource

答案 3 :(得分:0)

使用范围集合并运行取决于当前登录用户的查询

ActiveAdmin.register Shipment do
  controller do
    def scoped_collection
      my_scope = resource_class.unscoped
      return my_scope if current_admin_user.role == "administrator" # return everything
      my_scope.where(customer_id: current_admin_user.customer_id) # filter by signed in user
    end
  end
end