Ruby on rails 如果Rails模型中存在关联,如何别名属性?
仅当关联Ruby on rails 如果Rails模型中存在关联,如何别名属性?,ruby-on-rails,associations,alias,Ruby On Rails,Associations,Alias,仅当关联公司存在时,我想别名名称属性,如果不存在,则返回竞争对手self.name 在Rails 6中,最好的方法是什么 我试图使用alias\u属性,但它总是将名称化名为公司 # == Schema Information # # Table name: competitors # # id :uuid not null, primary key # name :string # url :string # create
公司
存在时,我想别名名称
属性,如果不存在,则返回竞争对手self.name
在Rails 6中,最好的方法是什么
我试图使用alias\u属性
,但它总是将名称
化名为公司
# == 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
#==架构信息
#
#表名:竞争对手
#
#id:uuid不为空,主键
#名称:string
#url:string
#创建时间:datetime非空
#更新时间:datetime非空
#公司id:uuid
#
#索引
#
#公司id(公司id)上的索引(公司id)唯一,其中(公司id不为空)
#
类竞争对手
覆盖名称怎么样
de name
company.name || super
end
我认为alias不适合这里我认为您最好使用一个实例方法,不要认为alias适用于可以在这里使用的
super
<代码>公司名称| | super