On Rails Console, tried to find some data. Model: User
class User < ApplicationRecord
scope :active, -> { where(status: true) }
scope :inactive, -> { where(status: false) }
end
Rails Console
users = User.all
User Load (0.8ms) SELECT `users`.* FROM `users` LIMIT 11
Output - User objects
#<ActiveRecord::Relation [#<User id: 1, name: "John", status: true >,#<User id: 2, name: "Micheal", status: false >,#<User id: 3, name: "Denis", status: true >,#<User id: 4, name: "Arnold", status: true> ...]>
Now try to find an active user from the above object.
active_users = users.active
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`status` = TRUE LIMIT 11
Output - Users with active status
#<ActiveRecord::Relation [#<User id: 1, name: "John", status: true >,#<User id: 3, name: "Denis", status: true >,#<User id: 4, name: "Arnold", status: true > ...]>
Here, tried to find the active users from the ActiveRecord Object, but somehow SQL query ran at the database instead of filtering records within the object.
Is this the right way to filter objects or any other approach?
activeas the column name with a boolean type right?activewould make a lot more sense as a boolean. But you could also use an enum instead of a boolean. railstips.org/blog/archives/2012/10/10/…