【问题标题】:PostgreSQL Rails has_many :through / collection_singular_ids / :order problemPostgreSQL Rails has_many :through / collection_singular_ids / :order 问题
【发布时间】:2011-11-06 15:25:00
【问题描述】:

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

关于如何解决这个问题的任何想法? 谢谢,

【问题讨论】:

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


    【解决方案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"...
    

    【讨论】:

    • 德克斯特,它不工作。这是错误:ActiveRecord::StatementInvalid: PGError: ERROR: syntax error at or near "DISTINCT" LINE 1: SELECT counties.name, DISTINCT "activity_areas".county_id FR...。生成的sql为SELECT counties.name, 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
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2014-09-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多