通过attr_accessor排序模型对象 [英] Order model objects by an attr_accessor

查看:77
本文介绍了通过attr_accessor排序模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我必须对对象列表进行排序时,我认为attr_accessor具有与其他行为相同的行为,但是似乎有所不同:

I thought that attr_accessor has the same behavior as the other when I have to sort a list of objects, but it seems that is different:

  dataRecords = MyData.where("day = ?", Time.now.yesterday.strftime("%Y%m%d").to_i)
  dataRecords.each do |data|
    data.accessor_var = func(data.x, data.y)
  end
  @sortedData = dataRecords.order('accessor_var DESC')

但是@sortedData没有被排序...

but @sortedData is not being sorted...

推荐答案

您需要记住,当将范围或订单应用于ActiveRecord::Relation时,将从表中重新加载数据.这意味着,当您遍历它们并更改属性时,除非保存结果,否则更改将不可用于下一个作用域调用.

You need to keep in mind that when you apply a scope or order to an ActiveRecord::Relation the data is reloaded from the table. This means that when you loop through them and change an attribute, unless you save the result the changes will not be available to the next scope call.

您可以使用sort_by代替,它将对内存而不是数据库中的对象起作用.

You can use sort_by instead which will work on the objects in memory rather than the database.

选项1:循环保存(可能对访问器的使用不多!)

Option 1: Save as you loop (probably not much use with an accessor!)

dataRecords = MyData.where("day = ?", Time.now.yesterday.strftime("%Y%m%d").to_i)
dataRecords.each do |data|
  data.accessor_var = func(data.x, data.y)
  data.save
end
@sortedData = dataRecords.order('accessor_var DESC') # Reload from table will include the saved values.

选项2:sort_by

Option 2: sort_by

dataRecords = MyData.where("day = ?", Time.now.yesterday.strftime("%Y%m%d").to_i)
dataRecords.each do |data|
  data.accessor_var = func(data.x, data.y)
end
@sortedData = dataRecords.sort_by{|data| data.accessor_var}

此外, toro2k 一旦了解了情况,就会为您的排序进行一些优化.

Also, toro2k has some nice optimisation for your sorting once you understand the situation.

这篇关于通过attr_accessor排序模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆