Alvin Lau Alvin Lau - 1 year ago 51
Ruby Question

Rails define nil check on record in model

I have a Rails application which stores information on children, certain fields would make a

anaphylactic and I want to be able to define a method in my
model so that I can perform a check on a record for anaphylaxis. For example a
is anaphylactic if 10 certain fields are
. I do not want to write out
@anaphylactic_kids = Kid.where( . . . and . . . and . . .)
as it would be really long. Is there a simpler way to do this? Thanks for all help!

Answer Source

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.

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

Now instead of using the full Kid.where statement in your controllers, you can simply call Kid.anaphylactic to get the same results.