简体   繁体   English

Ruby,使用“?” - db 或 model 方法?

[英]Ruby, use of '?' - db or model method?

I love using the?我喜欢使用? for boolean fields, eg, for 'animals' table "alive?"对于 boolean 字段,例如,对于“动物”表“活着?” is very obvious.非常明显。 Where do I define this?我在哪里定义这个? Do I name the db field with it when creating the table migration(don't think so).创建表迁移时是否用它命名db字段(不这么认为)。 Or is it automatic for boolean fields or do I have a little method in the active record model class for animals that says something like def alive?还是对于 boolean 字段是自动的,或者我在活动记录 model class 中是否有一些方法可以用于说 def alive 之类的动物? if alive then true else false end?如果活着那么真否则假结束?

Rails automatically generates a method ending in a ? Rails 自动生成一个以?结尾的方法for each of the fields in a model.对于 model 中的每个字段。 Some examples:一些例子:

Animal #=> Animal(id: integer, alive: boolean, name: string)
a = 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 that you can easily define your own ?另请注意,您可以轻松定义自己的? methods:方法:

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

This behaviour is automatic for all boolean fields in ActiveRecord.对于 ActiveRecord 中的所有 boolean 字段,此行为是自动的。

As an extra nicety, I like to name boolean fields with an is_ prefix.另外,我喜欢用is_前缀命名 boolean 字段。 is_alive , giving you is_alive? is_alive ,给你is_alive? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM