ruby-on-rails - Rails ActiveRecord 从列中获取值,如果为 nil,则从关联的默认值获取
问题描述
我确定这已得到解答,但我的搜索失败了。
我有两个模型:
class Person < ApplicationRecord
belongs_to :family
# has column "last_name"
end
class Family < ApplicationRecord
has_many :people
# has column "last_name"
end
我想Person.take.last_name
:
- 如果 Person 有一个
last_name
不是 nil 的,返回那个 - 如果此人有一个家庭,则返回该家庭的
last_name
- 否则,返回零。
我可以做类似的事情
class Person < ApplicationRecord
belongs_to :family
# has column "last_name"
def last_name_lookup
last_name || family&.last_name || nil
end
end
但是想知道是否有内置的 rails 方法可以做到这一点,或者是否认为掩盖列的真实值是不合适的。
解决方案
我不知道 Rails 的内置方式。但你可以做
# in person.rb
def last_name # yes, overrides the built-in getter
read_attribute(:last_name) || family&.last_name # will be nil if both last_names are nil
end
推荐阅读
- go - 从扩展添加虚拟表时如何提供表规范
- swift - 从 shouldChangeTextIn 更新 UITextView 值返回字符两次
- python - 如何使用多索引过滤器为列分配值?
- javascript - 通常将上下文应用于方法别名
- grouping - 从制表器下载 pdf 时保留 ColumnCalculations 的格式
- python - 启用以记录调试语句
- javascript - 如何在时事通讯表单上实施 Google 的 reCaptcha v3?
- javascript - 添加悬停效果以使用内联样式对 div 做出反应
- nginx - 当proxy_pass通过2个nginx时Websocket 404
- excel - 如果我在 VBA 中创建一个具有相同名称的新实例,会发生什么情况?