问题描述
|
我在订购应用程序中使用了Cancan,Devise,Rails 3。
每个用户通过协议都有很多公司。每个公司还通过协议拥有许多用户。
在我的能力模型中,我具有以下几点:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :super
can :manage,:all
elsif user.role? :admin
can :manage,[User,Company,Order]
elsif user.role? :tech
can :manage,Tech]
elsif user.role? :customer_admin
can [:read,:update],User,:id => user.id
can [:read,:id => user.id
can [:read ],Order,:id => user.id
end
end
end
当customer_admin登录时,我一直在尝试仅向他们显示与其关联的公司。在公司视图中,我可以看到用户列表很好。
在我的公司控制程序(索引)中,我尝试执行以下操作:
@usercompanies = Company.where([\'user_id = ?\',current_user.id ])
但是,这列出了错误的公司吗?
确保这是一个愚蠢的新手错误,但会感谢您的帮助。如果您还有其他需要,请告诉我。
解决方法
您可以使用cancan迅速添加限制,这也是我第一次必须设置它时令人费解。进行此设置的文档在这里。作为参考,您希望使控制器中的索引动作如下所示:
@usercompanies = Company.accessible_by(current_ability)
但是,在最新版的gem中,这应该在index操作中自动完成。我认为您在abilities.rb
中有一个错误,因为当您有一条记录并将其与用户相关联时,它通常会有一个名为user_id的列。您可能希望像这样使用它:
can [:read ],Order,:user_id => user.id
由于通常将属性“ 5”用作记录的唯一标识,而不是关联的标识。