2011-08-30 71 views
2

在遷移到Heroku的過程中,我有一個奇怪的錯誤,只有當我使用PostgreSQL(在MySQL工作正常)PostgreSQL的導軌的has_many:通過/ collection_singular_ids /:順序問題

當我執行@user.county_ids我得到以下錯誤:

ActiveRecord::StatementInvalid: PGError: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

LINE 1: ...id" WHERE ("activity_areas".user_id = 1) ORDER BY counties.n...

生成的SQL請求是:

SELECT DISTINCT "activity_areas".county_id FROM "activity_areas" INNER JOIN "counties" ON "counties"."id" = "activity_areas"."county_id" WHERE ("activity_areas".user_id = 1) ORDER BY counties.name ASC

終於型號:

class User < ActiveRecord::Base 
    has_many :activity_areas 
    has_many :counties, :through => :activity_areas 
end 

class ActivityArea < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :county 

    default_scope joins(:county).order("counties.name ASC") 
end 

class County < ActiveRecord::Base 
    has_many :activity_areas 
    has_many :users, :through => :activity_areas 

    default_scope :order => 'name ASC' 
end 

關於如何解決此問題的任何想法? 謝謝,

回答

1

說到PostgreSQL,請確保order by子句中的元素也出現在select子句中。 MySQL是這個規則:)

試一試更改活動區域模型的默認範圍還挺寬以

default_scope select('counties.name').joins(:county).order("counties.name ASC") 

這應該產生這樣

SELECT DISTINCT "activity_areas".county_id, counties.name FROM "activity_areas"... 
+0

德克斯特一個SQL,它不工作。這裏是錯誤:「ActiveRecord :: StatementInvalid:PGError:ERROR:在DISTINCT處或附近出現語法錯誤」第1行:SELECT COUNTY.NAME,DISTINCT「activity_areas」.county_id FR ...。生成的sql是「SELECT COUNTY.NAME,DISTINCT」activity_areas「.county_id FROM」activity_areas「INNER JOIN」COUNTY「ON」COUNTY「。」ID「=」activity_areas「。」county_id「WHERE(」activity_areas「.user_id = 1 )ORDER BY counties.name ASC' – Dorian