Reputation: 891
I'm sure this has been answered, but my searching is failing me.
I have two models:
class Person < ApplicationRecord
belongs_to :family
# has column "last_name"
end
class Family < ApplicationRecord
has_many :people
# has column "last_name"
end
I would like Person.take.last_name
to:
last_name
that is not nil, return thatlast_name
I could do something like
class Person < ApplicationRecord
belongs_to :family
# has column "last_name"
def last_name_lookup
last_name || family&.last_name || nil
end
end
But was wondering if there is a built-in rails way to do this, or if it's considered improper to mask a column's true value.
Upvotes: 0
Views: 550
Reputation: 6156
I don't know of a Rails built-in way. But you can do
# 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
Upvotes: 1