PostgreSQL Rails has_many:through / collection_singular_ids /:订单问题

时间:2011-08-30 09:07:25

标签: ruby-on-rails-3 postgresql has-many has-many-through

在迁移到heroku的过程中,只有在使用PostgreSQL时才会出现奇怪的错误(在Mysql中正常工作)

当我执行@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 个答案:

答案 0 :(得分:1)

说到PostgreSQL,请确保order by子句中的元素也出现在select子句中。 MySQL对此规则有点宽容:)

尝试将活动区域模型中的默认范围更改为

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

这应该生成类似

的SQL
SELECT DISTINCT "activity_areas".county_id, counties.name FROM "activity_areas"...