Shpigford
Shpigford

Reputation: 25348

Preventing a duplicate database call in a view

I have the following in one of my Rails views:

<% if response.response_variables.where(var_name: variable[0]).present? %>
   <%= response.response_variables.where(var_name: variable[0]).first.var_value %>
<% else %>
   Something else
<% end %>

Right now I'm doubling up on the database call doing the if/else. Is there a way to use the database call from the if statement so that I don't call the DB twice?

Upvotes: 0

Views: 67

Answers (2)

Gjaldon
Gjaldon

Reputation: 5644

First of all, it's best to keep logic minimal in your views so try to refactor your code so expose as little logic in your views as possible.

Anyway, here's how you could avoid unnecessary db calls:

<% response_variable = response.response_variables.find_by(var_name: variable[0]).includes(:var_value) %>
<% if response_variable %>
   <%= response_variable.var_value %>
<% else %>
   Something else
<% end %>

In the above code, we assume that var_value is an attribute of response_variable. If it isn't an attribute, you can remove the call to includes.

Hope that helps!

Upvotes: 2

BroiSatse
BroiSatse

Reputation: 44695

Try

<% if variable = response.response_variables.where(var_name: variable[0]).first %>
   <%= variable.var_value %>
<% else %>
   Something else
<% end %>

Note:

You probably should move this logic into your controller though.

Upvotes: 2

Related Questions