Skip to content

Instantly share code, notes, and snippets.

@mhluska
Last active September 13, 2018 12:21
Show Gist options
  • Save mhluska/2e0958fb5a740f81f9f9b8dbaf4ad694 to your computer and use it in GitHub Desktop.
Save mhluska/2e0958fb5a740f81f9f9b8dbaf4ad694 to your computer and use it in GitHub Desktop.
Rails Many-to-many relationship generating incorrect SQL
class User < ApplicationRecord
has_many :order_items_bought,
-> { joins(:order).where.not(orders: { state: :expired }).order(created_at: :desc) },
foreign_key: :buyer_id,
class_name: :OrderItem
has_many :videos_bought,
-> { joins(:orders).select('DISTINCT ON (videos.id) videos.*').reorder('videos.id DESC') },
through: :order_items_bought,
source: :item,
source_type: :Video do
def confirmed
where(orders: { state: :confirmed })
end
end
# user.videos_bought.confirmed generates this SQL:
# ```
# Video Load (47.0ms) SELECT DISTINCT ON (videos.id) videos.* FROM
# "videos" INNER JOIN "order_items" "order_items_videos_join" ON
# "order_items_videos_join"."item_id" = "videos"."id" AND "order_items_videos_join"."item_type" = $1 INNER JOIN
# "orders" ON "orders"."id" = "order_items_videos_join"."order_id" INNER JOIN
# "order_items" ON "videos"."id" = "order_items"."item_id" WHERE
# "order_items"."buyer_id" = $2 AND ("orders"."state" != $3) AND "order_items"."item_type" = $4 AND
# "orders"."state" = $5 ORDER BY videos.id DESC, "order_items"."created_at" DESC LIMIT $6
# ```
# Which returns some Video records which are joined with Orders that do NOT have state confirmed.
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment