【问题标题】:Rails 4.2.6 adding extra attributes to activerecord elementsRails 4.2.6 为 activerecord 元素添加额外的属性
【发布时间】:2017-08-16 21:20:14
【问题描述】:

我想在不先转换为 JSON 的情况下向查询结果添加额外字段。

我有3个模型teamtournamentmatch,关系如下:

class Match < ActiveRecord::Base
   belongs_to :homeTeam, class_name: "Team", foreign_key: "localTeam"
   belongs_to :awayTeam, class_name: "Team", foreign_key: "visitorTeam"

class Team < ActiveRecord::Base
   has_many :local_matches, class_name: "Match", foreign_key: "localTeam"
   has_many :visitor_matches, class_name: "Match", foreign_key: "visitorTeam"

class Tournament < ActiveRecord::Base
  has_many :matches, class_name:"Match",foreign_key: "tournamentId"

Tournament 类中,我正在尝试添加一个函数,该函数将为我提供锦标赛中所有比赛的列表,但对于每场比赛,它应该包含来自Teams 的一些数据(主队和客队)。

我正在尝试以下方法:

def tournament_matches
 matches= self.matches
 matches.each do |match|
  match[:home_team_logo] = match.homeTeam.logo //add this field
  match[:visitor_team_logo] = match.awayTeam.logo //add this field
 end
 matches.group_by(:round)
end

但我收到一个错误:
ActiveModel::MissingAttributeError: can't write unknown attribute 'local_team_name'

我该怎么做才能将Team 中的额外字段添加到我的ActiveRecord::Associations::CollectionProxy Match 返回类元素中?请记住,Team.logo 是一个函数,而不是一个属性。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord model


    【解决方案1】:

    您可以在 Team Model 中使用 attr_accessor 并将值存储在其中。它创建了一个在数据库中不存在的虚拟字段,但您可以使用match.homeTeam.&lt;attribute_name&gt; 访问它。您可以在此处阅读有关 attr_accessor 的信息:

    What is attr_accessor in Ruby?

    https://apidock.com/ruby/Module/attr_accessor

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多