PostgreSQL Rails has_many :through / collection_singular_ids / :order 问题
在迁移到heroku的过程中,只有当我使用PostgreSQL时才会出现奇怪的错误(在Mysql中工作正常)
当我执行@user.county_ids
时,我收到以下错误:
ActiveRecord:: StatementInvalid: PGError: ERROR: 对于 SELECT DISTINCT, ORDER BY 表达式必须出现在选择列表中
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) 排序依据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
知道如何解决这个问题吗? 谢谢,
In the process of migrating to heroku, I have a weird error only when I use PostgreSQL (works fine in Mysql)
When I execute @user.county_ids
I get the following error:
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...
The generated sql request is :
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
and finally the models:
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
Any idea on how to fix this?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于 PostgreSQL,请确保 order by 子句中的元素也存在于 select 子句中。 MySQL对此规则有点宽松:)
尝试将活动区域模型中的默认范围更改为
这应该生成类似的SQL
When it comes to PostgreSQL, ensure that the elements in order by clause are also present in the select clause. MySQL is kinda lenient on this rule :)
Try changing the default scope in activity area model to
This should generate a SQL like