Using question mark character in Rails/ActiveRecord column name

跟風遠走 提交于 2019-12-02 18:49:10
cdesrosiers

Rails will automatically generate the method smart? if there is a field named 'smart'.

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

Actually, Im using Rails 4 and I can't call my boolean column without the question mark

pry(main)> User.where(is_validated: false).first.is_validated
  User Load (0.9ms)  SELECT "users".* FROM "users" WHERE "users"."is_validated" = 'f' ORDER BY "users"."id" ASC LIMIT 1
=> nil
[13] pry(main)> User.where(is_validated: false).first.is_validated?
  User Load (0.8ms)  SELECT "users".* FROM "users" WHERE "users"."is_validated" = 'f' ORDER BY "users"."id" ASC LIMIT 1
=> false
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!