timpone
timpone

Reputation: 19969

how to check for non-nil value of associated attribute - is there a more succinct way?

I have items and they have prices in a has_one relationship. In the price object, there is a price value (unfortunately true). I'd like to be able to test for non-nil values of item.price.price. In the view, there is an add_to_order helper method that should show only if there is a price.price. I test using for this condition with:

<% if item.price && !item.price.price.nil? %>
  <%=add_to_order item %>
<% end %>

but it seems pretty ugly. Is there a more succinct / 'better' way of testing for this?

thx in advance

Upvotes: 3

Views: 105

Answers (3)

Kyle
Kyle

Reputation: 22258

I would try to avoid logic in your views and simply have your add_to_order method handle the item validation.

def add_to_order(item)
  return unless price = item.price.try(:price)
  # ... your implementation
  # the items price is in the price variable for you
end

Object#try

Your view would just become:

<%=add_to_order item %>

since all your logic would be in the add_to_order helper method.

Upvotes: 1

davidrac
davidrac

Reputation: 10738

You can use try. It will work safely even if item.price is nil

<% unless item.price.try(:price) %>
  <%=add_to_order item %>
<% end %>

Upvotes: 1

Daniel Evans
Daniel Evans

Reputation: 6808

Rails provides a syntax sugar for this with the try method:

<% unless item.price.try(price).nil? %>
  <%= add_to_order item %>
<% end %>

Upvotes: 1

Related Questions