LGFaler
LGFaler

Reputation: 126

Is there a way to chain conditionals in Ruby, Rails or ActiveRecord?

Sometimes I find myself doing something like:

def my_method
  item = SomeModel.where(some_attr: 'some_val').first
  (item) ? nil : item.method
end

This is to say that if item exists, return the results of item.method, but if it doesn't exist, just return nil or false.

I can more succinctly write this like this:

def my_method
  SomeModel.where(some_attr: 'some_val').first.try(:some_method)
end

I've heard that a rails rescue operation can be expensive, though. Is there something as succinct and elegant as the try that I could use in it's place?

Upvotes: 0

Views: 279

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

If you are positive there will be either single or none records returned, you might safely use an enumerator instead:

SomeModel.where(some_attr: 'some_val')
         .limit(1)
         .map(&:some_method)
         .first

Upvotes: 2

Related Questions