Reputation: 35
I have followed a few tutorials and starting to understand the syntax.
I am trying to build a real world working application - a marketplace (like an AirBnB).
Should I create 2 user models (seller_user, buyer_user)? of have 1 User model and define roles differently using CanCan or similar?
Whats the best rails way to do this?
Upvotes: 0
Views: 798
Reputation: 1415
Add a roles
column to User
table.
rails g migration AddRoleToUsers role:string
Then use Cancancan
gem.
https://github.com/CanCanCommunity/cancancan
Read cancancan
readme.
You can set what access Users have with the ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
else
can :read, :all
end
end
end
The above shows that a user.admin? can view the full crud of any model. If you're not admin you can only read any model.
You might want to use active_admin
gem to control the app on the backend.
Have fun!
Upvotes: 0
Reputation: 153
One possible solution is to make the User class be used only for login and the user would belong to a Renter or Tenant via a polymorphic association, as in:
class User < ActiveRecord::Base
belongs_to :identifiable, :polymorphic => true
end
If you don't know what polymorphic associations are, you should read this tutorial.
This code would be used like this:
subscriber = Tenant.find(1)
user = User.new
user.identifiable = tenant
user.save
So, your Tenant or Renter is going to be related to one user, the :identifiable field is a relationship (a polymorphic relationship) to another object.
With this a user could use this identifiable association to be a Tenant or a Renter and your SessionsController would be reused for both of them (and all the authentication logic too, since it would live inside of User and not these other classes).
Upvotes: 1