sql – 如何在rails中指定连接的表的条件

我正在使用ActiveRecord在Rails中进行查询,该连接指定了连接表上的某些条件。我似乎无法让它上​​班,即使我按照这里的例子:

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

从guide.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

但是有一个column submission.task_id,您可以在db模式中看到它。我可以成功地做到这一点:

SELECT "submissions".* FROM "submissions" WHERE "submissions"."task_id" = 1
子句中的名称应该是复数,以引用表名:

Score.joins(:submission).where(:submissions => {:task_id => 1})
http://stackoverflow.com/questions/9033797/how-to-specify-conditions-on-joined-tables-in-rails

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:sql – 如何在rails中指定连接的表的条件