[英]Rails define nil check on record in model
I have a Rails application which stores information on children, certain fields would make a child
anaphylactic and I want to be able to define a method in my Child
model so that I can perform a check on a record for anaphylaxis. 我有一个Rails应用程序,该应用程序存储有关儿童的信息,某些字段会使
child
过敏,并且我希望能够在Child
模型中定义一个方法,以便可以对过敏反应记录进行检查。 For example a child
is anaphylactic if 10 certain fields are nil
. 例如,如果10个特定字段
nil
则child
是过敏性的。 I do not want to write out @anaphylactic_kids = Kid.where( . . . and . . . and . . .)
as it would be really long. 我不想写出
@anaphylactic_kids = Kid.where( . . . and . . . and . . .)
因为它确实很长。 Is there a simpler way to do this? 有没有更简单的方法可以做到这一点? Thanks for all help!
感谢所有帮助!
There isn't an easy way to avoid writing the full where
clause out at least once, but you can avoid having to write it into every controller action you want to use it in by creating a scope for it. 没有一种简单的方法可以避免将完整的
where
子句至少写出一次,但是您可以通过为其创建作用域来避免将其写入要使用它的每个控制器操作中。
In your model, add this method: 在模型中,添加以下方法:
def self.anaphylactic
Kid.where(:field1 => nil, :field2 => nil, :field3 => nil)
# complete the where clause for every field you need to check
end
Now instead of using the full Kid.where
statement in your controllers, you can simply call Kid.anaphylactic
to get the same results. 现在,您
Kid.where
在控制器中使用完整的Kid.where
语句,只需调用Kid.anaphylactic
即可获得相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.