簡體   English   中英

如果當前對象的屬性為nil(jsonb類型),則創建返回關聯對象的屬性值的方法

[英]Create method that returns associated object's attribute value if current object's attribute is nil (jsonb type)

我有以下兩個類:

class Account < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb

  has_one :plan
end

class Plan < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb
end

並將調用這樣的功能:

account.features    # being account is an instance of Account
# or
account.features[:feature_key]

問題是我希望account在其自身內部查找featuresfeatures[:feature_key] ,如果它是nilempty ,則應從關聯的Plan對象中選擇值。

就像是:

features.present? ? features : plan.features
# and
features[:feature_key].present ? features[:feature_key] : plan.features[:feature_key]

但是在Account類中使用適當的方法

嗯,這不是最佳實踐,但您可以使用自定義方法覆蓋getter。 在你的情況下:

def features
  return features[:feature_key] if features[:feature_key].present?
  return plan&.features[:feature_key] if plan&.features[:feature_key].present?
end

不確定這是你需要的邏輯,但如果你把它放在Account模型中,這將適用於覆蓋。 執行此操作的首選方法是將方法命名為else,並調用該方法,以便在需要時仍可訪問未修改的屬性。

不確定我完全理解,但根據其他答案給出你的評論我假設你正在尋找類似的東西:

class Account < ActiveRecord::Base 

  def feature_info(key)
    return plan.features[key] unless features.present? && features[key].present?
    features[key]
  end 
end

然后稱為

   account = Account.first
   account.feature_info(:feature_key)

這可能更干凈

class Account < ActiveRecord::Base 
  def features 
    read_attribute(:features) || {} 
  end
  def feature_info(key)
    return plan.features[key] unless features[key].present?
    features[key]
  end 
end

暫無
暫無

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

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