I want to set a variable to a given value, but only if the value is valid.
Right now this is the code I have:
if Something.find(params[:id].comments.first.exists?
@comment = Something.find(params[:id]).comments.first
else
@comment = nil
end
But this is inefficient because it has to load the records twice.
I tried to use the ruby method try
to ensure that the variable would only be set if the value is valid:
@comment = Something.try.find(params[:id]).comments.first
but no matter where I put it, I get back a "nil is not a symbol" error. It seems try
is only for printing variables.
Anyone know how else I can accomplish this with only one query?