I needed to write a method that always returns an integer value. If the record is non-existent, the method returns 0
I have a unique index on the columns being queried and came up with two solutions:
# Option a) Ruby logic
def some_method id
result = Model.some_scope.find(:first,
conditions: { foo_id: id },
select: :int_value)
# Return 0 if record does not exist:
( result.nil? ? 0 : result.int_value )
end
# Option b) Allow Postgres to do the work
def some_method id
# sum() returns 0 if the record wasn't found
Model.some_scope.where(foo_id: id).sum(:int_value)
end
Because of the unique index, both methods return the same value.
Is there any reason one solution is better than the other, aside from brevity?
My inclination is to choose the solution based on server resources, i.e. minimizing database server load by giving the job to Ruby.
Running Ruby 1.9.3 and Postgres 9.1
You don't need the (possibly more expensive) aggregate function sum()
.
Use SQL-COALESCE()
for that.
COALESCE
is probably the cheapest way. But the cost is so tiny, it does not matter either way.