Reputation: 133
I want to add extra fields to the results of a query without first converting to JSON.
I have 3 models team
, tournament
and match
, with the following relationship:
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"
In the Tournament
class, I'm trying to add a function that will give me a list of all matches in the tournamet, but for each match it should include some data from theTeam
s involved in it (homeTeam and awayTeam).
I'm trying the following:
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
But I get an error:
ActiveModel::MissingAttributeError: can't write unknown attribute 'local_team_name'
What can I do so that I can add extra fields from Team
to my ActiveRecord::Associations::CollectionProxy
Match
class elements in the return? Keep in mind that Team.logo
is a function, not an attribute.
Upvotes: 0
Views: 828
Reputation: 1227
you can use attr_accessor in Team Model and store values in it. It creates a virtual field which doesn't exists in Database but you will be able to access it using match.homeTeam.<attribute_name>
. you can read about attr_accessor here:
Upvotes: 1