Alvin Lau
Alvin Lau

Reputation: 101

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!

Upvotes: 1

Views: 145

Answers (1)

ArtOfCode
ArtOfCode

Reputation: 5712

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.

Upvotes: 4

Related Questions