在迁移到heroku的过程中,只有在使用PostgreSQL时出现奇怪的错误(在Mysql中工作正常)
当我执行 @user.county_ids
时,出现以下错误:
ActiveRecord::StatementInvalid: PGError: ERROR: 对于 SELECT DISTINCT,ORDER BY 表达式必须出现在选择列表中
第 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县名 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
知道如何解决这个问题吗? 谢谢,
最佳答案
对于 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"...
关于ruby-on-rails-3 - PostgreSQL Rails has_many :through/collection_singular_ids/:order problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7240920/