首页 > 解决方案 > 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

我可以做类似的事情

class Person < ApplicationRecord
    belongs_to :family
    # has column "last_name"

    def last_name_lookup
        last_name || family&.last_name || nil
    end
end

但是想知道是否有内置的 rails 方法可以做到这一点,或者是否认为掩盖列的真实值是不合适的。

标签: ruby-on-railsrubyactiverecord

解决方案


我不知道 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

推荐阅读