Best place to store model specific constants in rails 3.1?

牧云@^-^@ 提交于 2019-12-02 17:13:16

Something like:

class User < ActiveRecord::Base

  TYPES = %w{ mom dad grandmother grandfather son }

  TYPES.each_with_index do |meth, index|
    define_method("#{meth}?") { type == index }
  end

end


u = User.new
u.type = 4
u.mom? # => false
u.son? # => true

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.

You should avoid using "type" as a model's column name unless you use Single Table Inheritance.

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance

One way you be to write an file in initializers folder or lib folder

say app_contants.rb and in this file you can write

MOM=1

DAD=2
  1. Incase you write a initializer you can do

user.type == mom

2.If you create an lib file make it a module

 module app_constants
    mom = 1
    dad = 2
  end 

and simply include this module wherever you need

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!