简体   繁体   English

如果对象不存在,在ruby中忽略错误的简单方法

[英]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.

相关问题 Ruby on Rails检测到用户,但仍返回不存在的错误 - Ruby on Rails detecting a user, but still returning an error that it doesn't exist ArticlesController的未定义方法`action&#39;(表不存在):Class - Ruby on Rails错误 - undefined method `action' for ArticlesController(Table doesn't exist):Class - Ruby on Rails error 尚不存在的RSpec存根对象 - RSpec stub object that doesn't exist yet 可以对表中不存在的字段使用简单表单吗? - Can use Simple form for fields that doesn't exist in table? 即使父项不存在,Ruby on Rails也会创建子项? - Ruby on Rails creates child even if parent doesn't exist? Heroku上的Cloud9中的Ruby on Rails应用“不存在” - Ruby on Rails app in Cloud9 “doesn't exist” on Heroku Ruby on Rails / Heroku-您要查找的页面不存在 - Ruby on Rails / Heroku - The page you were looking for doesn't exist ruby on rails关联-删除关联中不存在的内容 - ruby on rails associations - removing something which doesn't exist in the association Ruby on rails,测试表明一列不存在,但在架构上 - Ruby on rails , test is saying a column doesn't exist but its on the schema 来自控制台的Ruby on rails - (表不存在) - Ruby on rails from console - (Table doesn't exist)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM