Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda