【发布时间】:2017-08-16 21:20:14
【问题描述】:
我想在不先转换为 JSON 的情况下向查询结果添加额外字段。
我有3个模型team、tournament和match,关系如下:
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