Make a Mysql query that finds data just before another (in RoR)
I'm making this query to MySql
Image.find( :all,
:conditions => ["created_at > ? && 开发者_开发问答approved = 1", @image.created_at],
:order => "created_at DESC", :limit => 5)
However, I want the images create just before the given image was created at. Right now, it's returning a list of images from the top of the list, that were create much, much before that image. How can I do this?
Your current query will find any images newer than @image because your using >. You'll need to decide what kind of range you're wanting to look in.. What time frame do you consider "just before"? Minutes? Seconds?
To find all images created within 5 mins of @image, try:
Image.find(:all, :conditions => ["(created_at > ? and created_at < ?) and approved = 1", @image.created_at.advance(:minutes => -5), @image.created_at])
My solution feels more like a hack, but I'm not sure of a better one. I set :order => "created_at ASC"... and then reversed the resulting array, and got the response I wanted. Hrm.
精彩评论