Reputation: 43
CASE
I am working on a model which is composed of the following tables:
The relations I am looking for are:
has_many
comments. has_many
comments.has_many
users.belongs_to
a company.Meaning basically that users would be able to login, reference their information such as name, last_name, etc... But a user could be a simple visitor or could be a company's employee.
e.g, users will have the choice, but not mandatory, to assign themselves a company they currently belongs_to
.
APPROACH
I was thinking in a way to accomplish this:
Creating 2 users tables, one could be employees the other one visitors for instance. But it doesn't seem to cover the case where you change your status, for example, if you don't want to belongs_to
a company anymore, this approach seems inefficient.
Or using a boolean column in my users table, "employee?", :boolean, default: false
. I am not sure how to handle this tho. How to switch from false to true and assign a user to a company and vise versa?
QUESTION
Is there a way through one single users table to handle both status -visitors and employees- and dynamically switch from a category to another?
Thanks in advance
Upvotes: 1
Views: 121
Reputation: 2860
You may do it with two steps:
1.Make belongs_to
relation optional:
# User model
belongs_to :company, optional: true
2.Make scopes and methods to differ visitors and employees:
# User model
scope :visitors, -> { where(company: nil) }
scope :employees, -> { where.not(company: nil) }
def visitor?
company_id.nil?
end
def employee?
!visitor?
end
That's it. Now you can do like this:
User.visitors
User.employees
User.find(id).visitor?
Upvotes: 2