Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify conditions on joined tables in rails

I am trying to do a query in in Rails with ActiveRecord that specifies some condition on a joined table. And i can't seem to get it to work, even though i follow the examples from here:

http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables

From the guides:

Client.joins(:orders).where(:orders => {:created_at => time_range})

My database schema looks like this, with tables scores, submissions and 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 

So i want to do a query where I can find all "scores" that have a relation to a spesific task. Submission belongs to tasks and scores.

My query now looks like this:

Score.joins(:submission).where(:submission => {:task_id => 1}) 

This generates the following syntax:

SELECT "scores".* FROM "scores" INNER JOIN "submissions" ON "submissions"."score_id" = "scores"."id" WHERE "submission"."task_id" = 1 

Which generates the following error:

SQLite3::SQLException: no such column: submission.task_id 

But there is a column submission.task_id, which you can see in the db schema. And i can do this successfully:

SELECT "submissions".* FROM "submissions" WHERE "submissions"."task_id" = 1 
like image 454
espenhogbakk Avatar asked Jan 27 '12 13:01

espenhogbakk


1 Answers

The name in the clause should be plural to reference the table name:

Score.joins(:submission).where(:submissions => {:task_id => 1}) 
like image 140
Nick Avatar answered Sep 22 '22 09:09

Nick