【发布时间】:2019-11-26 03:03:32
【问题描述】:
我有一个项目需要在不同的页面中显示集合或关联,并在列表中显示 id 顺序。数据库是 PostgreSQL。
一般情况下,数据会默认按照 id 的顺序存储。但是,我的数据库不是这样的,如果您不申请订单,我的数据库总是会以不同的顺序返回,即 [1432, 1430, 1401, 1400]。
目前我必须为每个关联手动添加订单范围。但它看起来很挑剔。即使在一个模型中,我也必须多次添加。
class A
has_many :xxx, -> { order(:id)}
has_many :yyy, -> { order(:id)}
has_many :zzz, -> { order(:id)}
end
class B
has_many :aaa, -> { order(:id)}
has_many :bbb, -> { order(:id)}
has_many :xxx, -> { order(:id)}
end
...
因此,我正在寻找更好的解决方案。我能想到的一种解决方案是将default_scope 添加到ActiveRecord::Base 类。不过听说default_scope是反派?
class ApplicationRecord < ActiveRecord::Base
default_scope { order(:id) }
end
请随时给我任何建议。谢谢。
【问题讨论】:
-
这个
will always return in a different order if you don't apply orders是什么意思?您能否尝试通过示例进行解释以更好地理解问题? -
@Gabbar 我的意思是它不会以 id 顺序返回。例如,
@library.books向我返回 id[5,4,3,2,1],但我希望是[1,2,3,4,5] -
如果你只想按 id 订购,那么你可以这样做 -
has_many :xxx, -> { order("id ASC")}, class_name: 'B', foreign_key: 'b_id'。让我知道它是否对您有帮助。 -
@Gabbar 感谢您的回答。但你可能不明白我的问题。我的问题与几个表甚至整个数据库有关。