我试图用ActiveRecord在Rails中进行查询,该查询在连接的表上指定了一些条件。即使我遵循此处的示例,我似乎也无法使其正常工作:
http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables
从guides:
我的数据库架构如下所示,带有表scores
,submissions
和tasks
:
create_table "scores", :force => true do |t|
t.integer "value"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "scores", ["user_id"], :name => "index_scores_on_user_id"
create_table "submissions", :force => true do |t|
t.integer "user_id"
t.integer "task_id"
t.integer "score_id"
t.datetime "completed_at"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "submissions", ["score_id"], :name => "index_submissions_on_score_id"
add_index "submissions", ["task_id"], :name => "index_submissions_on_task_id"
add_index "submissions", ["user_id"], :name => "index_submissions_on_user_id"
create_table "tasks", :force => true do |t|
t.integer "episode_id"
t.integer "score"
t.string "key"
t.datetime "created_at"
t.datetime "updated_at"
end
所以我想做一个查询,在这里我可以找到与特殊任务有关的所有“分数”。提交属于任务和分数。
我的查询现在看起来像这样:
Score.joins(:submission).where(:submission => {:task_id => 1})
这将生成以下语法:
SELECT "scores".* FROM "scores" INNER JOIN "submissions" ON "submissions"."score_id" = "scores"."id" WHERE "submission"."task_id" = 1
会产生以下错误:
SQLite3::SQLException: no such column: submission.task_id
但是有一列
submission.task_id
,您可以在数据库模式中看到它。我可以成功做到这一点:SELECT "submissions".* FROM "submissions" WHERE "submissions"."task_id" = 1
最佳答案
子句中的名称应为复数形式以引用表名称:
Score.joins(:submission).where(:submissions => {:task_id => 1})