2011-08-30 5 views
2

heroku로 마이그레이션하는 과정에서 PostgreSQL을 사용할 때만 이상한 오류가 발생합니다 (MySQL에서 잘 작동합니다).PostgreSQL Rails has_many : through/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은

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

덱스터 같은 SQL을 생성해야

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

이이 규칙 :

시도는 활동 영역 모델의 기본 범위 변경에 좀 ​​관대 한, 그것은 작동하지 않습니다. 다음은 오류입니다 :'ActiveRecord :: StatementInvalid : PGError : ERROR : "DISTINCT"또는 근처에서 구문 오류 LINE 1 : counties.name, DISTINCT "activity_areas".county_id FR ...'. 생성 된 sql은 'SELECT counties.name, DISTINCT "activity_areas".county_id FROM "activity_areas"INNER JOIN "카운티"ON "county". "id"= "activity_areas". "county_id"WHERE ("activity_areas".user_id = 1) ORDER BY counties.name ASC' – Dorian