简体   繁体   English

Ruby on Rails-条件语句

[英]Ruby on Rails - conditional statement

I have the following method 我有以下方法

def providers
  if super.present?
    super.map(&:name).join("#{I18n.t('healtherecord_engine.shared.provider_name_separator')}<br>").html_safe
  else
    I18n.t('healtherecord_engine.data.no_data')
  end
end

The provider has the following model schema 提供者具有以下模型架构

"providers": [
    {
      "name": "",
      "relationship": ""
    }
  ],

The problem is, when the provider has a blank "name" and has a "relationship", it displays "nothing" - just a blank. 问题是,当提供程序的“名称”为空白并且“关系”为空时,它显示“无”-仅是空白。 I still want it to display a "--"(I18n.t('healtherecord_engine.data.no_data')). 我仍然希望它显示一个“-”(I18n.t('healtherecord_engine.data.no_data'))。

I tried doing this, 我尝试这样做

def providers
  names = super.map(&:name).join("#{I18n.t('healtherecord_engine.shared.provider_name_separator')}<br>")
  names.present? ? names.html_safe : I18n.t('healtherecord_engine.data.no_data')
end

Still no luck. 仍然没有运气。 What am I doing wrong here? 我在这里做错了什么? Can anyone show me some direction with this? 谁能告诉我一些指导吗? Thank you in advance 先感谢您

To avoid confusion, I18n.t('healtherecord_engine.shared.provider_name_separator') = "," I18n.t('healtherecord_engine.data.no_data') = "--" 为避免混淆,I18n.t('healtherecord_engine.shared.provider_name_separator')=“,” I18n.t('healtherecord_engine.data.no_data')=“-”

Change: 更改:

if super.present?

to

if super && super.any?(&:name)

Also note that calling super multiple times might be dangerous: 另请注意,多次调用超级可能很危险:

prov_hash = super
if prov_hash && prov_hash.any?(&:name)

Quite likely it can be further optimized, but this depends on the super method. 它很有可能可以进一步优化,但这取决于超级方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM