Best way to handle different types of users?

I have a large Rails application that has 34 different types of users through Single Table Inheritance. When the application was originally designed, it was assumed that the User would have different types of behavior based on the type. This assumption was wrong, so I'm looking for refactoring.

The question is, how would you reorganize your custom STI?

  • Add a ton of logical attributes for the user (i.e. User#is_employee?, User.is_contractor?)
  • Rename User#typeto User#user_typeand just do field-based string matching
  • Invalid search table solution
  • Something I'm missing ...

To clarify, the user needs a “type” for ACL reasons, but with STI they are really just empty models, and STI causes specification problems, general pain in the ass, etc.

+3
source share
3 answers

Are all 34 models empty?

If you can do this:

self.inheritance_column = nil

At the top of the user model, you can simply check the type:

if @user.type == "Employee"
  # do something
end
0
source

It looks like you really need roles, not user types. I found that this usually happens when you get many types of users, because some users have more than one role.

ACL: , . - , .

, ​​ , , (!).

@user.can_view_payroll_info_for?(@employee, 2.years.ago) ==> true
@user.can_view_payroll_info_for?(@employee, Time.now) ==> false

, :

@john.has_role(:content_author) ==> true
@john.has_role(:moderator) ==> true

@benny.has_role(:content_author) ==> true
@benny.has_role(:moderator) ==> false

@michael.has_role(:moderator) ==> true
@michael.has_role(:content_author) ==> false

() "" , , .

+3

, , " ACL" , ...

, User#user_type. , , . . ( , ), method_missing 1.

:

def method_missing(method, *args, &block)
 if(method.to_s.starts_with?('is_'))
  self.user_type == method.to_s.gsub("is_", "").gsub("?", "")
 end
end

true is_contractor?, user_type .

, gsub . , - .

0

Source: https://habr.com/ru/post/1720138/


All Articles