I'm pretty new to Rails, and I would like to know if there is a way to had an "expired_at" field using the gems "Rolify", so I could add a Role to an User for a while, or permanent Role if field is NULL.
I thought of adding the field into the migration :
class RolifyCreateRoles < ActiveRecord::Migration[6.1]
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end
create_table(:users_roles, :id => false) do |t|
t.references :user
t.references :role
t.datetime :expired_at # Adding field to the "join_table"
end
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:users_roles, [ :user_id, :role_id ])
end
end
But I don't have any idea about how to "override" the methods like "add_role" or "has_role?" to take this "expired_at" field into consideration, so I could do something like :
room = Chat::Room.find(1)
sarah = User.find(1)
david = User.find(2)
# Today
sarah.add_role :muted, room, 7.days.from_now
david.add_role :muted, room
sarah.has_role? :muted, room # should return true
david.has_role? :muted, room # should return true
# A week later
sarah.has_role? :muted, room # should return false
david.has_role? :muted, room # should return true
Thanks.
i have an idea that you don't need to add
expired_atfield, you can extendrolifygem to append the expired time after the role name, then we can parse the expired time and check whether that role is expired or not, take a look following code:demo