问题
If a user is logged in with a specific role - vendor
- they should only see items that they have created in their store. 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).
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
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 (i.e. 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. However, a buyer (i.e. a user with role :buyer
) should be able to see all the products from all buyers (as will an admin/etc). 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?
回答1:
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.
来源:https://stackoverflow.com/questions/15407491/how-do-i-restrict-the-currently-logged-in-user-to-only-see-products-that-belong