如果 Rails 模型中存在关联,如何给属性起别名?
How to alias attribute if association exists in Rails model?
我想仅在关联 company
存在时为 name
属性起别名,如果不存在则给 return 竞争对手 self.name
。
在 Rails 6 中最好的方法是什么?
我尝试使用 alias_attribute
,但它总是将 name
别名为 company
。
# == Schema Information
#
# Table name: competitors
#
# id :uuid not null, primary key
# name :string
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# company_id :uuid
#
# Indexes
#
# index_competitors_on_company_id (company_id) UNIQUE WHERE (company_id IS NOT NULL)
#
class Competitor < ActiveRecord::Base
belongs_to :company
alias_attribute :name, :company_name
def company_name
company.name
end
end
只覆盖名称怎么样
de name
company.name || super
end
我认为别名不适合这里
也许有一个很好的方法可以通过委托
来实现你的目标
delegate :name, to: :company, prefix: true, allow_nil: true
:prefix => :fancy
和 :allow_nil => true
等选项允许您根据需要调整委托方法。
以上示例使方法 company_name
可用。这在一般情况下可能很有用,在其他人建议的访问器中也是如此。
def name
company_name || super
end
我想仅在关联 company
存在时为 name
属性起别名,如果不存在则给 return 竞争对手 self.name
。
在 Rails 6 中最好的方法是什么?
我尝试使用 alias_attribute
,但它总是将 name
别名为 company
。
# == Schema Information
#
# Table name: competitors
#
# id :uuid not null, primary key
# name :string
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# company_id :uuid
#
# Indexes
#
# index_competitors_on_company_id (company_id) UNIQUE WHERE (company_id IS NOT NULL)
#
class Competitor < ActiveRecord::Base
belongs_to :company
alias_attribute :name, :company_name
def company_name
company.name
end
end
只覆盖名称怎么样
de name
company.name || super
end
我认为别名不适合这里
也许有一个很好的方法可以通过委托
来实现你的目标delegate :name, to: :company, prefix: true, allow_nil: true
:prefix => :fancy
和 :allow_nil => true
等选项允许您根据需要调整委托方法。
以上示例使方法 company_name
可用。这在一般情况下可能很有用,在其他人建议的访问器中也是如此。
def name
company_name || super
end