簡體   English   中英

Ruby on Rails-條件語句

[英]Ruby on Rails - conditional statement

我有以下方法

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

提供者具有以下模型架構

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

問題是,當提供程序的“名稱”為空白並且“關系”為空時,它顯示“無”-僅是空白。 我仍然希望它顯示一個“-”(I18n.t('healtherecord_engine.data.no_data'))。

我嘗試這樣做

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

仍然沒有運氣。 我在這里做錯了什么? 誰能告訴我一些指導嗎? 先感謝您

為避免混淆,I18n.t('healtherecord_engine.shared.provider_name_separator')=“,” I18n.t('healtherecord_engine.data.no_data')=“-”

更改:

if super.present?

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

另請注意,多次調用超級可能很危險:

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

它很有可能可以進一步優化,但這取決於超級方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM