Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如果Rails模型中存在关联,如何别名属性?_Ruby On Rails_Associations_Alias - Fatal编程技术网

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