Auliya Fadli
Auliya Fadli

Reputation: 87

ruby on rails, how to using try() method in this case

I have a rails tag to call an attribute from an object like this

<%= item.product.name %>

but I got the error undefined method 'product' for nilClass. I've tried to use try() method like in the following code, it allows nill object from product,

<%= item.try(:[], 'product') %>,

but I don't know how to get name attribute from product now.

edited: i try this code item.try(:product).try(:[], :name) the same code like mr @Andrey Daineko and mr @santhosh suggest, this is the result if product not nill, its work enter image description here

but it's still give this error if product is nill,

enter image description here

Upvotes: 1

Views: 3200

Answers (2)

Santhosh
Santhosh

Reputation: 29124

You call try on the return value of try

item.try(:product).try(:name)

or if product is a Hash,

item.try(:product).try(:[], :name)

Upvotes: 4

Andrey Deineko
Andrey Deineko

Reputation: 52357

Use safe navigation (available from Ruby 2.3.0):

item&.product&.name 
# for Ruby < 2.3.0
item.try(:product).try(:name)

For hashes use Hash#dig (available from Ruby 2.3.0):

hash.dig(:foo, :bar, :baz) 
# for Ruby < 2.3.0
hash.fetch(:foo, {}).fetch(:bar, {}).fetch(:baz, {})

Upvotes: 3

Related Questions