Hi. I would like to do code refactoring: @beers = Beer.all.each do |beer| unless @beers.find{|c| c.brand_id == beer.brand_id} @beers << beer end break if @beers.size > 29 end
So I achieved this by writing scope (on PostgreSQL):
scope :with_unique_brand, select("DISTINCT ON (beers.brand_id) beers.*")
Using this scope alone is working correct, however chaining that scope with order method, throws strange error:
Beer.with_unique_brand.order("created_at"):
Beer Load (1.1ms) SELECT * FROM (SELECT DISTINCT ON (beers.brand_id) beers.* FROM "beers") AS id_list ORDER BY id_list.alias_0 PGError: ERROR: column id_list.alias_0 does not exist LINE 1: ...and_id) beers.* FROM "beers") AS id_list ORDER BY id_list.al... ^ : SELECT * FROM (SELECT DISTINCT ON (beers.brand_id) beers.* FROM "beers") AS id_list ORDER BY id_list.alias_0 PGError: ERROR: column id_list.alias_0 does not exist LINE 1: ...and_id) beers.* FROM "beers") AS id_list ORDER BY id_list.al... ^ : SELECT * FROM (SELECT DISTINCT ON (beers.brand_id) beers.* FROM "beers") AS id_list ORDER BY id_list.alias_0
Any idea why?