Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong order on has_many association when upgrading from rails 3 to rails 4

I am trying to update one project from Rails 3 to Rails 4. In Rails 3 I was doing:

class Sale < ActiveRecord::Base
  has_many :windows, :dependent => :destroy
  has_many :tint_codes, :through => :windows, :uniq => true, :order => 'code ASC'
  has_many :tint_types, :through => :tint_codes, :uniq => true, :order => 'value ASC'
end

When I call sale.tint_types, it does the following query in Rails 3:

SELECT DISTINCT "tint_types".* FROM "tint_types" INNER JOIN "tint_codes" ON "tint_types"."id" = "tint_codes"."tint_type_id" INNER JOIN "windows" ON "tint_codes"."id" = "windows"."tint_code_id" WHERE "windows"."sale_id" = 2 ORDER BY value ASC

I updated it for Rails 4 like this:

class Sale < ActiveRecord::Base
  has_many :windows, :dependent => :destroy
  has_many :tint_codes, -> { order('code').uniq }, :through => :windows
  has_many :tint_types, -> { order('value').uniq }, :through => :tint_codes
end

The query changes to:

SELECT DISTINCT "tint_types".* FROM "tint_types" INNER JOIN "tint_codes" ON "tint_types"."id" = "tint_codes"."tint_type_id" INNER JOIN "windows" ON "tint_codes"."id" = "windows"."tint_code_id" WHERE "windows"."sale_id" = $1  ORDER BY value, code

It adds code in the order clause and this makes PostgreSQL to through an error. I assume that it's because of the scope, but I can't figure out how to get that ORDER BY code out.

Any help is appreciated, Thanks!

like image 684
st3fan Avatar asked Oct 31 '13 15:10

st3fan


1 Answers

The Rails community helped me to find the solution.

class Sale < ActiveRecord::Base
  has_many :windows, :dependent => :destroy
  has_many :tint_codes, -> { order('code').uniq }, :through => :windows
  has_many :tint_types, -> { uniq }, :through => :tint_codes

  def tint_types
    super.reorder(nil).order(:width => :asc)
  end
end

For more details see https://github.com/rails/rails/issues/12719.

like image 171
st3fan Avatar answered Oct 19 '22 14:10

st3fan