开发者

Is there an easy way to get the record number N in a query?

What I would like to achieve, could be (in an inefficient way) done like this:

records = SomeModel.where(:some_field => "some value").all
required_record = records[n]

... where n is the given position of the record in the scoped (by "where") results.

It's inefficient for big tables, ob开发者_StackOverflowviously. Is there a way to achieve this without fetching all the records?


Use a combination of offset and limit to only fetch the row you want. For example, to get only the 5th result:

SomeModel.where(:some_field => "some value").offset(5).limit(1)


Er, I'm not sure I understand your question... Databases generally don't care about orders of rows, so are you ordering by the field? If so, you can use something like the rank() function in PostgreSQL (http://www.postgresql.org/docs/current/static/tutorial-window.html).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜