1

私は2つのモデルteamとを持っていfixtureます。fixtureモデルには2つの列がhome_team_idあり、主キーaway_teamの外部キーが含まれていteamます。

フィクスチャテーブルのhome_team_idとを使用してチーム名を取得できるselectクエリを実行しようとしています。away_team_id

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

フィクスチャコントローラでSQLクエリを実行する必要がありますか?それをfixtureビューに表示するにはどうすればよいですか?

これは私がクエリに対して試したものですが、運がありませんでした。私の備品ショーで私は持っていました:

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

1 に答える 1

7

モデルを次のように書き直します。

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

これで、コントローラーでこれを行うことができます。

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

そしてこれはあなたの見解では:

<p>Away Team: <%= @fixture.away_team.name %></p>
<p>Home Team: <%= @fixture.home_team.name %></p>
于 2013-01-01T18:39:17.747 に答える