如果当前对象的属性为nil(jsonb类型),则创建返回相关对象的属性值的方法

时间:2019-05-29 17:32:19

标签: ruby-on-rails ruby hash ruby-on-rails-5

我有以下两个课程:

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类中使用适当的方法

2 个答案:

答案 0 :(得分:0)

不是最佳实践,但是您可以使用自定义方法覆盖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模型中,它将对替代有效。首选的方法是将方法命名为其他名称,然后调用该方法,以便在需要时仍可以访问未修改的属性。

答案 1 :(得分:0)

不确定我是否完全理解,但是鉴于您在其他答案下的评论,我假设您正在寻找类似的东西:

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