activerecord - Ruby, use of '?' - db or model method? -



activerecord - Ruby, use of '?' - db or model method? -

i love using ? boolean fields, e.g, 'animals' table "alive?" obvious. define this? name db field when creating table migration(don't think so). or automatic boolean fields or have little method in active record model class animals says def alive? if live true else false end ?

rails automatically generates method ending in ? each of fields in model. examples:

animal #=> animal(id: integer, alive: boolean, name: string) = animal.new a.alive #=> nil a.alive? #=> false a.alive = true a.alive? #=> true a.name #=> nil a.name? #=> false a.name = "giraffe" a.name? #=> true

also note can define own ? methods:

class animal def young? created_at > 1.day.ago end end

ruby-on-rails activerecord

Comments

Popular posts from this blog

java - How to pass parameters between Request-Scoped Controllers? -

string - what is the difference between "some" == "some\0" and strcmp("some","some\0") in c++? -

actionscript 3 - Flex: moving a point with rotation doesnt change the point XY? -