Alvin Lau Alvin Lau - 3 months ago 7
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

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. For example a
child
is anaphylactic if 10 certain fields are
nil
. 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

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
end

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