ruby-on-rails-3 - PostgreSQL Rails has_many :through/collection_singular_ids/:order problem

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

在迁移到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/

相关文章:

ruby-on-rails - rails I18n : error 'translation missing' when i try translate this words "off"

PostgreSQL/JDBC 和 TIMESTAMP 与 TIMESTAMPTZ

json - 使用列值作为对象键创建 json

ruby-on-rails - Rails 关联(belongs_to、has_many)无法使用创建方法(用户、帖子、评论)在表中保存 2 个 ID

ruby-on-rails - 为什么belongs_to/has_many 和 inverse_of 不能自动水合另一边?

model - ExtJS 4 : Understanding hasMany and belongsTo

ruby-on-rails-3 - before_destroy 回调中未加载关联

mysql - Rails 3 - 如何从 mysql 表中查找最后插入的 ID

ruby-on-rails - 在 Rails 3.2 App 中使用多个模型时,如何使用 Devise 处理身份验证

sql - 将行合并为一个结果并将结果添加为 SQL 中的不同值