简体   繁体   中英

Using rails has_scope gem to scope the last x number of items in array

I'm using the has_scope gem.

I want to scope the last x number of items in an array of Articles in my database

something like this:

scope :last_few_items, -> num { Article.last(num) }

so in my querystring I could say www.bla.com?last_few_items=2 to return the last 2 items of an array

but all the examples I see for has_scope use this syntax:

scope :scope_name, -> vartopass { where(attribute_val: vartopass)}

wher 'attribute_val' are all attributes from my database... so I'm not really sure how to get what I want... aside from making a new route and a new controller that defines @articles = Article.last(2) or something like that

This is extracted from your question:

wher 'attribute_val' are all attributes from my database... so I'm not really sure how to get what I want... aside from making a new route and a new controller that defines @articles = Article.last(2) or something like that

Did you tried it? This is actually the right way to do it, Rails natively implement last(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM