use*_*888 1 ruby mysql sql select ruby-on-rails
我有两个型号team和fixture.该fixture模型有两列home_team_id和away_team其中包含的外键team的主键.
我正在尝试进行选择查询,我可以使用夹具表中的home_team_id和来获取团队名称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
Run Code Online (Sandbox Code Playgroud)
我是否需要在Fixtures控制器中执行SQL查询,然后如何在我的fixture视图中显示它?
这是我尝试查询但没有运气.在我的灯具秀中我有:
<p>
<b>Home team:</b>
<%= Team.find_by_sql("SELECT name FROM teams WHERE team.id = fixtures_home_team_id") %>
</p>
Run Code Online (Sandbox Code Playgroud)
像这样重写你的模型:
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
Run Code Online (Sandbox Code Playgroud)
现在您可以在控制器中执行此操作:
@fixture = Fixture.find(params[:id])
Run Code Online (Sandbox Code Playgroud)
这在你看来:
<p>Away Team: <%= @fixture.away_team.name %></p>
<p>Home Team: <%= @fixture.home_team.name %></p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |