Best place to store model specific constants in rails 3.1?

后端 未结 4 1019
遥遥无期
遥遥无期 2021-01-31 04:54

I have a field type in a model called user which is an int in the db. The value of the int speficies the type of store it is. Example:

4条回答
  •  甜味超标
    2021-01-31 05:44

    Since Rails 4.1, there is support for ActiveRecord::Enum.

    There's a useful tutorial here, but in short:

    # models/user.rb
    class User < ActiveRecord::Base
      enum family_role: [ :mum, :dad, :grandmother]
    end
    
    # logic elsewhere
    u = User.first
    u.family_role = 'mum'
    u.mum? # => true
    u.family_role # => 'mum'
    

    Note: To convert from your current scheme (where your database already stores numbers corresponding to values), you should use the hash syntax:

    enum family_role: { mum: 0, dad: 1, grandmother: 2 }
    

    I would additionally propose that you reserve 0 for the default state, but that's just one convention and not critical.

提交回复
热议问题