Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

263
Views
how do you add constant value from a rails model

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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"
over 4 years ago · Santiago Trujillo Report

0

@aRtoo

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

user = User.first

user.read_attribute_before_type_cast(:priority_num)

gives you an integer of enum status

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!