我想在沒有先轉換爲JSON的情況下將額外的字段添加到查詢的結果中。Rails 4.2.6爲activerecord元素添加額外的屬性
我有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
類,我想增加一個功能,這將使我在所有比賽的名單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'
我能做些什麼,這樣我可以從Team
我ActiveRecord::Associations::CollectionProxy
Match
類元素添加額外的字段在回報?請記住,Team.logo
是一個函數,而不是一個屬性。