开发者

Select 7 items with ids centered on id 'n'

For the set of Foobars with the following ids:

1  2  3   5  7   9  11  15  18  19  22 23

I need a way to return the Foobars with the following ids, based on ActiveRecord:

baz(1) -> 1 2 3 5 7 9 11

baz(9) -> 3 5 7 9 11 15 18

baz(22) -> 9 11 15 18 19 22 23

This must be compatible with Ruby on Rails 2.3.9 (no Arel). It can't be done by simply subtracting and adding 3 from id n, because there may be gaps in the IDs.

edit: Here's what I did in the end:

firstseg = Foobar.all(:conditions => ["id <= " + params[:id]],
    :limit=> 4, :order => "id desc").reverse

@Foobars = firstseg + 开发者_如何学运维Foobars.all(:conditions => ["id > " + params[:id]],
    :limit => (7 - firstseg.length).to_s, :order => "id asc")

render 'showthem'


Try this:

class Foo
  def snow_white_and_six_dwarfs
    [ 
      Foo.all(:conditions => ["id < ?", id], :limit => 3, :order => "id ASC"),
      self,
      Foo.all(:conditions => ["id > ?", id], :limit => 3, :order => "id ASC")
    ].flatten
  end
end

Now

foo.snow_white_and_six_dwarfs

OR

Foo.find(9).snow_white_and_six_dwarfs


don't know if there is a better way, but you can do always do something like this:

def baz center_id
  all_ids = Foobar.find(:all, :select => "id", :order => "id ASC").collect &:id
  center_index = center_id ? all_ids.index(center_id) : nil

  if center_index
    Foobar.find(all_ids[center_index-3..center_index+3])
  else
    []
  end
end

this way, you use the index of the sorted ids instead of the ids themselves. Be careful though, if your center index is less than 3, you will have negative indices, so it will pick ids from the end of the array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜