接下来,previous记录使用命名范围 [英] Next, Previous Records Using Named Scope
问题描述
我有,我要检索下一个记录(S)和previous结果的模型。我想通过模型上的named_scope要做到这一点,同时也传递作为参数的下一个/ previous记录在X号返回。
I have a model for which I want to retrieve the next record(s) and previous record(s). I want to do this via a named_scope on the model, and also pass in as an argument the X number of next/previous records to return.
例如,假设我有5个记录:
For example, let's say I have 5 records:
- 记录1
- RECORD2
- RECORD3
- RECORD4
- Record5
我希望能够调用模型。$ P $ pvious或模型。$ P $ pvious(1)返回RECORD2。同样,我希望能够调用Model.next或Model.next(1)返回RECORD4。再举一个例子我希望能够调用模型。$ P $ pvious(2)返回RECORD3。我觉得你的想法。
I want to be able to call Model.previous or Model.previous(1) to return Record2. Similarly, I want to be able to call Model.next or Model.next(1) to return Record4. As another example I want to be able to call Model.previous(2) to return Record3. I think you get the idea.
我怎样才能做到这一点?
How can I accomplish this?
推荐答案
要实现类似'模式。previous',类本身就必须有一个当前的状态。这将使意义,如果当前的记录(或许在发布调度系统?)是RECORD3在你的榜样,但你的例子并不表明这一点。
To implement something like 'Model.previous', the class itself would have to have a 'current' state. That would make sense if the 'current' record (perhaps in a publishing scheduling system?) was Record3 in your example, but your example doesn't suggest this.
如果你想利用一个模型的实例,并获得下一个或previous记录,下面是一个简单的例子:
If you want to take an instance of a model and get the next or previous record, the following is a simple example:
class Page < ActiveRecord::Base
def previous(offset = 0)
self.class.first(:conditions => ['id < ?', self.id], :limit => 1, :offset => offset, :order => "id DESC")
end
def next(offset = 0)
self.class.first(:conditions => ['id > ?', self.id], :limit => 1, :offset => offset, :order => "id ASC")
end
end
如果这样你可以这样做:
If so you could do something like:
@page = Page.find(4)
@page.previous
另外的工作将是:
Also working would be:
@page.previous(1)
@page.next
@page.next(1)
显然,这种假设的'下一个'和'previous'的理念是由'身份证'字段,这可能是没有在应用程序的寿命延长很好。
Obviously, this assumes that the idea of 'next' and 'previous' is by the 'id' field, which probably wouldn't extend very well over the life of an application.
如果你确实想使用这个类上,你也许可以扩展该到一个名为范围,是以当前记录作为参数。事情是这样的:
If you did want to use this on the class, you could perhaps extend this into a named scope that takes the 'current' record as an argument. Something like this:
named_scope :previous, lambda { |current, offset| { :conditions => ['id < ?', current], :limit => 1, :offset => offset, :order => "id DESC" }}
这意味着你可以调用:
Which means you could call:
Page.previous(4,1)
在哪里'4'是要启动对记录的ID,1是要导航回的数量。
Where '4' is the id of the record you want to start on, and 1 is the number you want to navigate back.
这篇关于接下来,previous记录使用命名范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!