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

时间:2012-01-27 13:17:33

标签: sql ruby-on-rails activerecord

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

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

来自guides

  

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

我的数据库架构如下所示,包含表scoressubmissionstasks

  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,您可以在db模式中看到它。我可以成功地做到这一点:

SELECT "submissions".* FROM "submissions" WHERE "submissions"."task_id" = 1

5 个答案:

答案 0 :(得分:62)

子句中的名称应为复数以引用表名:

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

答案 1 :(得分:7)

子句名称应为复数以引用表名。

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

如果分数有很多提交,则连接符号也应该是复数,以引用分数和提交之间的关系。

Score.joins(:submissions).where(submissions: { task_id: 1 })

答案 2 :(得分:4)

警告:如果您使用非标准表名,上述内容将会失败:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "submissions"

要解决此问题,请将(joined-model-class).table_name作为密钥放在where哈希:

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

答案 3 :(得分:3)

我发现这更容易。

Score.joins(:submission).merge(Submission.where(task_id: 1))

答案 4 :(得分:1)

您的查询如下所示:

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

您的#joins是正确的,但:submission应为复数:

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