【问题标题】:SQL Query Ruby On RailsSQL 查询 Ruby On Rails
【发布时间】:2012-12-16 06:57:30
【问题描述】:

我有两个型号teamfixturefixture 模型有两列home_team_idaway_team,其中包含team 的主键的外键。

我正在尝试进行选择查询,我可以使用夹具表中的home_team_idaway_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>

【问题讨论】:

  • 您的Team 类中有2 个has_many :fixtures 关系,这可能是个问题...
  • 您的查询显示为FROM teams,但您的对象名为team。无论如何,您是否收到了一些错误消息? “没有运气”并没有告诉我们太多......

标签: mysql sql ruby-on-rails ruby select


【解决方案1】:

像这样重写你的模型:

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>

【讨论】:

  • 感谢很好的回答,完美运行,已经一个多星期试图用我自己编写的不同 sql 查询来解决这个问题,但你的回答让它变得简单了很多
  • 您知道在 Rails 中使用外键的任何好的教程或任何好的解释的链接吗?只是我没有看到它在我之前遵循的示例中使用过,我假设 Rails 只是知道它是一个外键,因为它最后是 _team_id。
  • 您几乎猜对了,只是您没有为每个关联指定唯一的名称。关联名称是唯一必须指定的部分,其他一切都取决于使用的约定。我建议从this guide 开始,您可以使用this railscast 跟进以获得更好的解释。
猜你喜欢
  • 1970-01-01
  • 2012-06-10
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多