在CashTransaction
模型中,我有默认范围:
class CashTransaction < ApplicationRecord
belongs_to :cashbook
default_scope { order(id_number: :desc) }
end
在一项服务中,我使用关联来提取cash_transactions:
def parsed_cash_transactions
cashbook.cash_transactions.map do |cash_transaction|
{
position: cash_transaction.id_number,
# ...
# other data
}
end
end
我在代码的其他位置使用此方法来创建虾表和许多其他相关内容:
def transaction_items
@last_position = parsed_cash_transactions.last[:position]
parsed_cash_transactions.each do |cash_transaction|
# ...
# some other actions
end
事情是默认范围在这里不起作用-大多数是正确的,但是transaction_items
方法返回了我随机混合的数据(例如,我在10处有位置2,在200处有11,依此类推...)。如何对这些transaction_items
数据进行排序id_number
?
default_scope
可能是Rails最糟糕的部分之一,应不惜一切代价避免。*
如果您经常执行一些特殊的订购,则只能创建自定义范围。
scope :ordered, -> { order(id_number: :desc) }
#
cashbook.cash_transactions.ordered
*当然这有点夸张,但事实default_scope
是事实,这是您必须非常警惕的,因为它与关联和其他内容一起使用的方式非常违反直觉。
https://riptutorial.com/ruby-on-rails/example/17746/beware-of--default-scope
https://www.reddit.com/r/rails/comments/ha6gqj/default_scope_is_evil/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句