首页 > 解决方案 > 如果当前对象的属性为 nil(jsonb 类型),则创建返回关联对象的属性值的方法

问题描述

我有以下两个课程:

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寻找,如果是,或者features它应该从关联的对象中选择值。features[:feature_key]nilemptyPlan

就像是:

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

但是在Account类中的适当方法中

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

解决方案


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

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

推荐阅读