Rails 3在.where条件之后使用NOT NULL排序 [英] Rails 3 sort after .where condition using NOT NULL

查看:144
本文介绍了Rails 3在.where条件之后使用NOT NULL排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的排名显示了最快的用户:

I have a ranking which shows the fastest User:

@users = User.find.sort { |a, b| b.finished_at <=> a.created_at }

现在我要添加一些代码,以防止在用户完成操作之前由于finish_at蜂nil而收到错误消息.

Now I hat to add some code to prevent getting an error because of finished_at beeing nil until the user finished.

@users = User.find(:all, :conditions => "finished_at IS NOT NULL").sort { |a, b| b.finished_at <=> a.created_at }

但是sort不起作用.这种链接方法是否有缺陷?并且find(:all, :conditions => "finished_at IS NOT NULL")滑轨是三向还是过时?

But sort doesn't work. Is this way of chaining methods flawed? And is find(:all, :conditions => "finished_at IS NOT NULL") the rails 3 way or outdated?

预先感谢

推荐答案

查询此问题的3种方法是:

The rails 3 way to query this would be:

@users = User.where('finished_at IS NOT NULL') 

对于排序,是的,可以像这样进行链接.一个简单的排序(全部都放在一个字段中)在sql中会更好:

As for the sort, yes, it's ok to chain like that. A simple sort, where it was all on a single field, would be better in sql:

@users = User.where('finished_at IS NOT NULL').order(:finished_at)

但是,您的排序做了一些奇怪的事情,将左侧的一个字段与右侧的另一个字段进行了比较.我认为您的排序算法无法正常工作,因为它将取决于初始记录顺序.由于您是将苹果与橙子进行比较,因此并不一致.

However, your sort does something weird, comparing one field on the left and another on the right. I don't think your sort algorithm is going to work right, as it will depend on the initial record order. Since you are comparing apples to oranges, it's not going to be consistent.

您说的是最快的用户",这使我认为您真的想要created_at时间与Finished_at时间之间的时差:

You said "the fastest user", which makes me think you really want the time difference between the created_at and finished_at times:

@users = User.where('finished_at IS NOT NULL').
              sort {|a,b| (a.finished_at - a.created_at) <=> (b.finished_at - b.created_at)

但是,如果要让Rails 3延迟加载该负载,则必须在sql中进行排序,而不是在ruby中进行排序.我认为这应该在mysql中起作用:

If you want to let rails 3 lazy load that, however, you have to sort in the sql, instead of in ruby. This should work in mysql I think:

@users = User.where('finished_at IS NOT NULL').
              select('users.*, timediff(finished_at,created_at) AS duration').
              order('duration')

这样,在实际调用值之前,将不会执行查询,这在需要页面缓存时会有所帮助.您还可以享受持续时间的好处:

This way, the query won't be executed until values are actually called for, which helps if you need page caching. You also have the benefit of having the duration available:

@users[0].duration

这篇关于Rails 3在.where条件之后使用NOT NULL排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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