Djjhjuser10735674
Djjhjuser10735674

Reputation: 27

User models and roles

What’s the best way to implement roles? Essentially what I want is one User model. But I want two different type of users. 1) regular user which they can Buy products. 2) second user is a seller. This user can add and delete products.

How can I add a seller to user? I would like the buyer and seller to have the same devise views. Can you give an example please?

Currently I have a user model(devise) and a products model.

Upvotes: 1

Views: 467

Answers (4)

Xero
Xero

Reputation: 4175

I don't know if it is the best way, but here an example how what can be done. Using enum :

 class User < ApplicationRecord

  devise :database_authenticatable, :rememberable, :trackable, :validatable, :lockable,
         authentication_keys: [:login], password_length: 4..32, unlock_strategy: :time

  enum available_roles: {buyer: 100, seller: 101}

  def buyer?
    has_role?(User.available_roles[:buyer])
  end

  def seller?
    has_role?(User.available_roles[:seller])
  end

  def has_role?(role)
    roles.include?(role)
  end

end

For using permissions (like only a seller can add and delete products) you can use the libary cancancan https://github.com/CanCanCommunity/cancancan

Upvotes: 0

shaivik
shaivik

Reputation: 343

What I would suggest is having different models and tables for customers and sellers as these are logically different entities. CustomerModel will interact with your client applications and SellerModel will interact with your internal application. This is a better way as far as I think.

Still if you wish to have them in single table I would suggest adding type column in the users table and then using the principles of Single table inheritance. The benefit you have with STI is that you can make your code much more modular and add methods specific to customers and sellers in their respective models which would in turn inherit from UserModel.

Here is a link for for single table inheritance which might be of some help: Single table inheritance explained

For access control you can use the Pundit gem. Here is a github link for the same.

Upvotes: 0

ray
ray

Reputation: 5552

You can add column user_type to user. You can set default to buyer or you can provide type select list to create/update form of user.

Further you can use cancancan gem to define permissions for them

Upvotes: 0

catmal
catmal

Reputation: 1758

You can use cancancan gem. And add a column seller(boolean) to users table.

Then on ability.rb

if user.present?
  can :read, Product
end

if user.seller?
 can :manage, Product, user_id: user.id     
end

This, assuming a product belongs to a user, will allow sellers to create/edit/delete their products(if products are common for all sellers you can remove the part user_id: user.id).

While all the rest (buyers) can see all products. If they buy probably they can create an order or whatever you will call it..

Upvotes: 2

Related Questions