[英]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.
在PHP中,您可以执行此操作,但我找不到针对ruby的推论。
您可以使用try
方法:
<%= @wine.brand.try(:name) %>
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 %>
You can use delegate
: 您可以使用
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. 这将创建
Wine#brand_name
方法,返回品牌name
,如果品牌不存在,则返回nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.