Katie M
Katie M

Reputation: 1131

Rails 3 - Object.try syntax

How would I avoid nil checks using Object.try for the following?

<%= image_tag(PeriodState.where("sla_id = ?", sla.id).last.state.image_file) %>

I've tried .try many different ways, but still receive errors, so my syntax is off. Thanks in advance!

Upvotes: 0

Views: 44

Answers (1)

Russell
Russell

Reputation: 12439

try isn't really appropriate for this: whatever the outcome image_tag will always be called - so you might end up calling it with nil. You need to check whether the image exists first then create an image tag only in this case. So I would get the PeriodState in your controller and have a simple if in your view:

# in controller
@period_state = PeriodState.where("sla_id = ?", sla.id).last

# in view 
<%= image_tag(@period_state.state.image_file) if @period_state %>

Of course this won't work if either state or image_file could also be nil.

Upvotes: 1

Related Questions