Brian Weinreich
Brian Weinreich

Reputation: 7702

Simple way in ruby to ignore error if object doesn't exist

I have two objects: Wine, Brand

Brand has_many :wines
Wine belongs_to :brand

How can I simplify the following code:

<%= @wine.brand.name if @wine.brand %>

I realize it's already very simple, but I have some different complexities in my code that make this cumbersome. What I'd like to do is something along the lines of:

<%= &@wine.brand.name %>

Where it basically ignores the error. In PHP you can do this, I just can't find a corollary for ruby.

Upvotes: 0

Views: 433

Answers (3)

Stefan
Stefan

Reputation: 114138

You can use delegate:

class Wine < ActiveRecord::Base
  belongs_to :brand
  delegate :name, to: :brand, prefix: true, allow_nil: true
end

This creates a Wine#brand_name method, returning either the brand's name or nil if brand does not exist.

Upvotes: 0

mcfinnigan
mcfinnigan

Reputation: 11638

I'd rather do this as follows:

class Wine  
  def brand_name
    brand.present? ? brand.name : ''
  end
end

This keeps your view slightly cleaner:

<%= @wine.brand_name %>

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

You can use try method:

<%= @wine.brand.try(:name) %>

Upvotes: 1

Related Questions