简体   繁体   English

如何限制当前登录的用户仅查看属于他们的产品?

[英]How do I restrict the currently logged in user to only see products that belong to them?

If a user is logged in with a specific role - vendor - they should only see items that they have created in their store. 如果用户以特定角色( vendor )登录,则他们应仅看到他们在商店中创建的项目。 They should not be able to see products from other vendors. 他们应该看不到其他供应商的产品。

So I am trying to do this in my authorization (using Devise, CanCan, Rolify). 因此,我试图在我的授权下执行此操作(使用Devise,CanCan,Rolify)。

I tried this: 我尝试了这个:

user ||= User.new # guest user (not logged in)
if user.has_role? :vendor
  can :dashboard
  can :manage, [Product, Vendor], :vendor_id => user.id
  can :view, [Product], :vendor_id => user.id
end

But....haven't had much luck with that...what am I missing? 但是。。。没有那么运气。。。我想念什么?

Edit 1 编辑1

I know that I can restrict the products in the controller like: 我知道我可以限制控制器中的产品,例如:

 @product = current_user.products

But that's not what I am looking for. 但这不是我想要的。 In this case, a vendor (ie user with role :vendor ) should only be able to see products they added to the store, but they shouldn't be able to see products that other vendors add. 在这种情况下,供应商(即具有角色:vendor用户)应该只能看到他们添加到商店中的产品,而他们应该看不到其他供应商添加的产品。 However, a buyer (ie a user with role :buyer ) should be able to see all the products from all buyers (as will an admin/etc). 但是,购买者(即,具有角色:buyer的用户)应该能够看到所有购买者的所有产品(管理员/等等)。 A buyer won't be able to see the prices, and some other attributes on some of the products, etc. 买方将无法看到价格以及某些产品的其他属性,等等。

How can I achieve all of that? 我该如何实现所有这些?

In the controller you can only find the products belonging to that user. 在控制器中,您只能找到属于该用户的产品。

def show
  @product = @user.products.find(params[:id])
  ...

Same applies to edit and update action. 同样适用于编辑和更新操作。 Cancan in this case is not required. 在这种情况下不需要Cancan。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果模型的父母只能属于其中一个,如何通过该父母映射关系? - How do I map an association through a model's parents if it can only belong to one of them? 如何将belongs_to限制为仅特定类型的用户? - how do I restrict belongs_to to only a specific type of user? 如何获取属于用户的所有记录并仅显示具有不同名称的记录? - How do I fetch all records which belong to a user and show only the records with distinct name? 如何仅显示属于某个用户的项目(使用restful_authentication)? - How do I only show items that belong to a certain user (using restful_authentication)? Rails + Devise:如何限制用户编辑不属于他的记录 - Rails + Devise: How to restrict a user from editing records that do not belong to him 如何限制角色不看到产品价格? - How do I restrict a role from not seeing prices on Products? 我当前以什么用户身份登录? - What user am I currently logged in as? Rails 3 ActiveAdmin CanCan。如何设置用户应该只看到属于他的记录? - Rails 3 ActiveAdmin CanCan. How to setup that User should only see records that belong to him? 当用户属于模型时如何命名用户名 - How do I call the name of a user when they belong to a model 如何防止访问属于不同用户的记录 - How do I prevent access to records that belong to a different user
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM