Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

sql - ActiveRecord Find - Skipping Records or Getting Every Nth Record

I'd like to do a query where I select a bunch of data, but I'd like to be able to then decrease the resolution of that data by only selecting, say, every third record, or maybe even every hundredth record, or whatever.

Is there any straightforward way to do this with ActiveRecord?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your Model has an ascending row like id without missing any number you can do something like this:

Model.all(:condition => "models.id%3=0")

If not you can first fetch all rows from the database and then you can do this:

models = Model.all
third_models = models.reject{ |model| models.index(model) % 3 != 0 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...