Home > database >  how do you add constant value from a rails model
how do you add constant value from a rails model

Time:10-14

I have users with many roles and I want to mark those roles with numbers or priority numbers.

Ex:

Admin - 4

Client - 3

User - 2

Guest - 1

instead of adding a new column on my roles table which will look like this

id name priority_num
1 Admin 4
2 Client 3
3 User 2
4 Guest 1

I was wondering if I could do it in my roles model class so I won't have to create a migration to my table and make it a constant value. Is this even possible?

CodePudding user response:

It should be as simple as:

class User
  def priority_num
    case name
    when 'Admin'
      4
    when 'Client'
      3
    when 'User'
      2
    when 'Guest'
      1
    else
      raise StandardError.new "#{name} does not have a priority_num configured"
    end
  end
end

However, I'd probably add the column myself incase this expands more, and to keep it queryable without having to duplicate the rules in external reporting tools.

CodePudding user response:

You can use enum to make it easier to identify roles in your model without adding new migration.

enum priority_num: {guest: 1, user: 2, client: 3, admin: 4}

User.first.priority_num will return "admin"

You can compare to check if user is admin like this:

user.priority_num == "admin"
  • Related