'Alias Rails Model with Scope as different class
I have a rails model with a scope that I would like to be able to use as a separate class for future semantics consistency. An example of this would be -
class User
scope :admin, => { where(admin: true) }
end
For my purposes, it's important that documentation and code is clearer than calling User.admin whenever I want to work with just admins, without creating a separate model. (Schema is identical, and there is more than 1 scope I need to move into a separate object).
My current solution is
class Admin
@@receiver = User.admin
def method_missing(m, *args, &block)
@@receiver.send(m, *args, &block)
end
def self.method_missing(m, *args, &block)
@@receiver.send(m, *args, &block)
end
end
This way, I can use Admin as an ActiveRecord::Relation where ever I need.
Is this an effective means of solving the issue? Because of gems we're running, I cannot inherit User, or it will start using STI and get really weird really quickly.
Solution 1:[1]
I believe the best approach would be to create Admin as a subclass of User with a default_scope.
class Admin < User
def self.default_scope
admin
end
#...
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
