ruby-on-rails - 如果当前对象的属性为 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]
nil
empty
Plan
就像是:
features.present? ? features : plan.features
# and
features[:feature_key].present ? features[:feature_key] : plan.features[:feature_key]
但是在Account
类中的适当方法中
解决方案
不确定我是否完全理解,但鉴于您在另一个答案下的评论,我假设您正在寻找类似的东西:
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
推荐阅读
- javascript - React Bootstrap ListGroup 实现类型的问题
- hl7-fhir - 使用 FHIR 对提供者/保险模型进行建模
- vulkan - 在任何 vulkan API 程序中,vkQueueSubmit 和 vkQueuePresent 都非常慢。我们如何解决这个问题?
- windows-installer - msiexec 日志 /lv 与 /l*v 之间的区别
- asp.net-core - 即使应用程序池的超时设置为 0,IIS 也会关闭网站
- sql - 我将如何编写 SQL 语句来查找子父对?
- python - 如何验证 Slack API 请求?
- google-maps - 在 ASP.NET CORE MVC 中集成 Google 地图需要帮助
- python - Scrapy链接列表
- amazon-web-services - 如何在不使用托管 UI 的情况下将 Cognito 用作 OAuth Flow?