2017-08-16 104 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是一個函數,而不是一個屬性。

回答