在Rails 3.2.11中为多个连接抛出模糊错误

时间:2013-12-02 14:25:20

标签: ruby-on-rails

我有一个问题:

User.select("distinct username as value, username as foto, roles.user_id as ID, 
followers as follower ").
where("username ILIKE ?", "%#{params[:term]}%").
joins(:identities).joins(:roles).all(conditions:{roles:{name: 'Creator'}})

user_id收到错误,因为我认为identities表也在使用它。

如何实际指定user_id列仅用于查询roles表?

任何变通办法都将受到赞赏。

编辑:

日志:

Rendered campaigns/_campaign_new.html.haml (27.7ms)
  User Load (1.1ms)  SELECT distinct username as value, user_id as ID, username as foto FROM "users" INNER JOIN "roles_users" ON "roles_users"."user_id" = "users"."id" INNER JOIN "roles" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."name" = 'Creator' AND (username ILIKE '%%')
  User Load (1.9ms)  SELECT distinct username as value, username as foto, user_id as ID, followers as follower FROM "users" INNER JOIN "identities" ON "identities"."user_id" = "users"."id" INNER JOIN "roles_users" ON "roles_users"."user_id" = "users"."id" INNER JOIN "roles" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."name" = 'Creator' AND (username ILIKE '%%')
PG::AmbiguousColumn: ERROR:  column reference "user_id" is ambiguous
LINE 1: ...ECT distinct username as value, username as foto, user_id as...
                                                             ^
: SELECT distinct username as value, username as foto, user_id as ID, followers as follower  FROM "users" INNER JOIN "identities" ON "identities"."user_id" = "users"."id" INNER JOIN "roles_users" ON "roles_users"."user_id" = "users"."id" INNER JOIN "roles" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."name" = 'Creator' AND (username ILIKE '%%')
  Rendered campaigns/new.js.erb (38.3ms)
Completed 500 Internal Server Error in 51ms

ActiveRecord::StatementInvalid - PG::AmbiguousColumn: ERROR:  column reference "user_id" is ambiguous
LINE 1: ...ECT distinct username as value, username as foto, user_id as...
                                                             ^
: SELECT distinct username as value, username as foto, user_id as ID, followers as follower  FROM "users" INNER JOIN "identities" ON "identities"."user_id" = "users"."id" INNER JOIN "roles_users" ON "roles_users"."user_id" = "users"."id" INNER JOIN "roles" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."name" = 'Creator' AND (username ILIKE '%%'):

1 个答案:

答案 0 :(得分:0)

您应该可以使用users.idroles_users.user_id

User.select("distinct username as value, username as foto, users.id as ID ...