【问题标题】:In rails, how to query fields in join table?在rails中,如何查询连接表中的字段?
【发布时间】:2014-11-29 14:28:58
【问题描述】:

在 Rails 中,我有两个模型,:contest:problem。每场比赛都有很多问题,一个问题可以属于很多比赛。一个问题在不同的比赛中,可能有不同的“索引”。

我使用模型:contest_problem 加入:contest:problem。在:contest_problem,我有一个字段index,用来标记比赛中问题的“索引”是什么。

现在,当我执行Contest.find(...).problems.find(...)... 是我要查询的竞赛 ID 或问题 ID)时,rails 将创建一个 sql 查询:

SELECT `problems`.*
    FROM `problems`
    INNER JOIN `contest_problems` ON `problems`.`id` = `contest_problems`.`problem_id`
    WHERE `contest_problems`.`contest_id` = 1 AND `problems`.`id` = 1
    LIMIT 1

我要执行这个 sql 查询:

SELECT `problems`.*, `contest_problems`.`index`
    FROM `problems`
    INNER JOIN `contest_problems` ON `problems`.`id` = `contest_problems`.`problem_id`
    WHERE `contest_problems`.`contest_id` = 1 AND `problems`.`id` = 1
    LIMIT 1

在rails中我应该怎么做?


型号:

class Contest < ActiveRecord::Base
  has_many :contest_problems
  has_many :problems, through: :contest_problems
end

class Problem < ActiveRecord::Base
  has_many :contest_problems
  has_many :contests, through: :contest_problems
end

class ContestProblem < ActiveRecord::Base
  belongs_to :contest
  belongs_to :problem
end

迁移:

class CreateContestProblems < ActiveRecord::Migration
  def change
    create_table :contest_problems do |t|
      t.integer :contest_id
      t.integer :problem_id
      t.string  :index,     limit: 2

      t.timestamps
    end
  end
end

【问题讨论】:

    标签: mysql sql ruby-on-rails


    【解决方案1】:

    试试这个查询:

    Problem.includes(:contests, :contest_ problems)
      .where(@problem.id)
      .where(contests: { id: @contest.id } ).first
    

    这将在一次数据库查询中为您提供所需的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2012-05-06
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      相关资源
      最近更新 更多