Using question mark character in Rails/ActiveRecord column name

前端 未结 3 352
长情又很酷
长情又很酷 2021-02-01 01:45

In keeping with Ruby\'s idiom of using a question mark in boolean methods (e.g. person.is_smart?), I\'d like to do the same for an ActiveRecord field in Rails:

3条回答
  •  佛祖请我去吃肉
    2021-02-01 02:24

    One "gotcha" to be aware of if you happen to use :enum in your model, since this stores the value as an integer. The question mark attr method provided by active record expects to evaluate 0 or 1 as false / true respectively in the database. For example:

    class Person
      enum mood: ['happy', 'sad', 'bored']
    end
    
    p = Person.new(mood: 'happy') # this would store mood as 0 in db
    p.mood? #=> false
    
    p.mood = 'sad' # saves as 1 in db
    p.mood? #=> true
    
    p.mood = 'bored' # saves as 2 in db
    p.mood? #=> true
    

    to see how this method works, see rails source

提交回复
热议问题