SQLite3 :: SQLException:不明确的列名:id:SELECT DISTINCT id FROM“tickets”

时间:2012-03-21 17:41:34

标签: ruby-on-rails ruby-on-rails-3

我真的不认为这个标题很好地解释了我想要做的事情,但我甚至不确定如何提问。

所以我有ticket has_many taskstask belongs_to account。我将此作为一个范围来返回票证任务属于某个帐户的票证列表:

scope :for_tasks_account, lambda { |account| joins(:tasks => :account ).where("accounts.id = ?", account.id) }

但它返回同一张票的多个,因为票证有多个帐户所属的任务。

我怎样才能让它只返回一张票,而不是为该帐号所属的票中的每个任务返回?

谢谢!

更新

我实际上想结合范围来列出适用于两个lambdas的所有内容:

scope :for_account, lambda { |account| joins(:group => :accounts ).where("accounts.id = ?", account.id) } || lambda { |account| joins(:tasks => :account ).where("accounts.id = ?", account.id) }

这可能吗?以及第一期。

更新2

我已经想出如何让两个查询合并,但我仍然在返回的查询中获得多个相同的票证。

  scope :for_group_with_account, lambda { |account| joins(:group => :accounts ).where("accounts.id = ?", account.id) }
  scope :for_task_with_account, lambda { |account| joins(:tasks => :account ).where("accounts.id = ?", account.id) }
  scope :for_account, lambda { |account| for_group_with_account(account) & for_task_with_account(account).select('DISTINCT id') }

我正在使用DISTICNT,但我仍然使用

SQLite3::SQLException: ambiguous column name: id: SELECT  DISTINCT id FROM "tickets" INNER JOIN "groups" ON "groups"."id" = "tickets"."group_id" INNER JOIN "assignments" ON "groups"."id" = "assignments"."group_id" INNER JOIN "accounts" ON "accounts"."id" = "assignments"."account_id" INNER JOIN "tasks" ON "tasks"."ticket_id" = "tickets"."id" INNER JOIN "accounts" "accounts_tasks" ON "accounts_tasks"."id" = "tasks"."account_id" WHERE ("tickets"."archived" IS NULL) AND (accounts.id = 20) LIMIT 20 OFFSET 0

再次感谢!

1 个答案:

答案 0 :(得分:0)

我认为你应该能够在这种情况下使用“distinct”。

scope :for_tasks_account, lambda { |account| joins(:tasks => :account ).where("accounts.id = ?", account.id).select('distinct accounts.id') }