user1014888
user1014888

Reputation: 431

SQL Query Ruby On Rails

I have two models team and fixture. The fixture model has two columns home_team_id and away_team which contain the foreign key of team's primary key.

I am trying to do a select query where I can get the team name using the home_team_id and away_team_id in the fixture table.

class Fixture < ActiveRecord::Base
    attr_accessible :away_score, :away_team_id, :home_score, :home_team_id, :result, :week
    belongs_to :team, :class_name => Team
end

class Team < ActiveRecord::Base
    attr_accessible :form, :name
    has_many :fixtures, :class_name => Fixture, :foreign_key => :home_team_id
    has_many :fixtures, :class_name => Fixture, :foreign_key => :away_team_id
end

Do I need to do the SQL query in the Fixtures controller, and how can I then show it in my fixture view?

This is what I tried for the query but had no luck. In my fixtures show I had:

<p>
  <b>Home team:</b>
  <%= Team.find_by_sql("SELECT name FROM teams WHERE team.id = fixtures_home_team_id")     %>
</p>

Upvotes: 1

Views: 334

Answers (1)

PinnyM
PinnyM

Reputation: 35531

Rewrite your models like this:

class Fixture < ActiveRecord::Base
  attr_accessible :away_score, :away_team_id, :home_score, :home_team_id, :result, :week
  belongs_to :home_team, :class_name => 'Team'
  belongs_to :away_team, :class_name => 'Team'
end

class Team < ActiveRecord::Base
  attr_accessible :form, :name
  has_many :home_fixtures, :class_name => 'Fixture', :foreign_key => :home_team_id
  has_many :away_fixtures, :class_name => 'Fixture', :foreign_key => :away_team_id
end

Now you can do this in your controller:

@fixture = Fixture.find(params[:id])

And this in your view:

<p>Away Team: <%= @fixture.away_team.name %></p>
<p>Home Team: <%= @fixture.home_team.name %></p>

Upvotes: 7

Related Questions