【发布时间】: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