2017-08-16 106 views
0

我想在没有先转换为JSON的情况下将额外的字段添加到查询的结果中。Rails 4.2.6为activerecord元素添加额外的属性

我有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类,我想增加一个功能,这将使我在所有比赛的名单tournamet,但是对于每场比赛,它应该包含来自其中的一些数据(主队和客场球队)。

我想以下几点:

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'

我能做些什么,这样我可以从TeamActiveRecord::Associations::CollectionProxyMatch类元素添加额外的字段在回报?请记住,Team.logo是一个函数,而不是一个属性。

回答