I have a model called note. I currently get notes like this:
current_user.notes.order('date DESC, created_at DESC').limit(10).reverse!
I now need to do the following:
Take a note_id parameter, and return 10 notes: the one from the parameter and 9 other ones ‘around’ the first.
Ideally, the 9 other notes will be allocated as 5 before the primary note and 4 after (or 4 before & 5 after), based on the ordering in the first line above.
Example:
note note note note primary_note note note note note note
Sometimes this will not be possible. For example if the primary_note is the users second note, it should return this:
note primary_note note note note note note note note note
Or if it’s the latest note, and the user only has 3 notes total, it should return:
note note primary_note
How can I do this? I’m using ruby 1.9.2 & Rails 3.0.1
I don’t think there is a way of obtaining those notes with a single query – you will need at least two. From my (somewhat limited) understanding of SQL, the only way you have to do that is:
primary_noteprimary_noteSomething similar to this (warning: untested code)
Usage:
But I could not think of a “chainable class method”. Maybe I don’t know enough SQL.
I don’t understand how you determine that you need “4” or “5” on this context. So I’m assuming that you know that.