Rails 4 Inner Join在同一张桌子上

时间:2016-03-23 18:08:52

标签: sql ruby-on-rails postgresql ruby-on-rails-4 join

在Rails 4应用程序中,我有以下关联:

User has_many :bookings
Booking belongs_to :client, class_name: "User"

我正在尝试通过表格加入以获取预订和客户端:

User.joins("INNER JOIN bookings on users.id = bookings.user_id").joins("INNER JOIN users on bookings.client_id = users.id") 

返回:

PG::DuplicateAlias: ERROR:  table name "users" specified more than once

是否有解决方案来获取2个关联?

1 个答案:

答案 0 :(得分:9)

尝试

User.joins("INNER JOIN bookings on users.id = bookings.user_id").joins("INNER JOIN users AS bookings_user on bookings.client_id = bookings_user.id")

请注意users AS bookings_user