Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

Change the tint_types association to

has_many :tint_types, -> { reorder('value').uniq }, :through => :tint_codes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top