简体   繁体   中英

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?

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.

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"

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM