1

我有两个模型teamfixture. 该fixture模型有两列home_team_idaway_team其中包含team主键的外键。

我正在尝试进行选择查询,我可以在其中使用夹具表中的home_team_idand获取团队名称。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

我是否需要在 Fixtures 控制器中执行 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

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>
于 2013-01-01T18:39:17.747 回答