我想在Rails中使用ActiveRecord執行查詢,指定連接表上的某些條件。我似乎無法得到它的工作,即使我跟隨的例子在這裏:如何指定軌道中連接表的條件
http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables
從上guides.rubyonrails.org指南:
Client.joins(:orders).where(:orders => {:created_at => time_range})
我的數據庫架構看起來是這樣的,得分,提交和任務表:
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
所以我想做一個查詢在哪裏可以找到所有的「分數」有關係的spesific任務。提交內容屬於任務和分數。
我的查詢現在看起來是這樣的:
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
事實上,根據Rails指南的片段發佈,所以應該使用'連接'符號。 – Chowlett 2012-01-27 13:29:46
你完全正確!只是發現我的自我。該死。 – espenhogbakk 2012-01-27 13:29:46
@Chowlett,那是因爲他們有多對多的關係,我只有一對一,has_one,has_many instad。這也是爲什麼我沒有把複數放在表格名稱上。 – espenhogbakk 2012-01-27 13:34:11