Kevin Brown
Kevin Brown

Reputation: 12650

Rails Kaminari pagination, set record index

I'm paginating using Kaminari pagination gem. I want to set the starting page, so the default page will be [0, 1, 2, 3, 4*, 5, 6,...].

My current pagination code:

@event = Event.order(start_date: :asc).page(params[:page]).per(1)
@items = Item.where(event_id: @event.first._id)

I want the first page displayed to be the most current event, so older events will be previous pages, and future events will be next pages.

Upvotes: 1

Views: 1426

Answers (3)

RustComet
RustComet

Reputation: 567

Your question is fairly broad so I am not sure exactly what you are looking for. If you just want to set the default page you could call something like

current_page = params[:page] ||= 4  #or whatever you want the default page to be

@event = Event.order(start_date: :asc).page(current_page).per(1)

UPDATE:

Similar to the answers below, you could use events occurring in the future to determine your page:

current_page = params[:page] ||= Event.where(:start_date > DateTime.now.utc).count #This will tell you how many events are in the future

@event = Event.order(start_date: :asc).page(current_page).per(1)

Upvotes: 0

sevenseacat
sevenseacat

Reputation: 25039

A way to do this would be to:

a) Count the events that are before the current date, eg. previous_events = Event.count(:start_date.lte => DateTime.now.utc)

b) Work out how many pages of events that covers, eg. previous_pages = previous_events/Event.default_per_page

c) Floor it to get the page you need to start on, eg. start_page = previous_pages.floor

Then pass this into your controller code:

@events = Event.order(start_date: :asc).page(start_page)

Upvotes: 1

DiegoSalazar
DiegoSalazar

Reputation: 13531

The SQL query that pagination uses adds LIMIT 1 OFFSET 0 to the end of the SQL statement. This means your result set will only have 1 record and you won't know at what index the current event is in. You'd have to do some more work to find the index out of all your events then pass that index as the OFFSET, i.e. the .page() method. Basically, get all of your events, find the event that is current, then get the index of it, and pass that index into your page method. Here's some pseudocode:

all_events = Event.order(start_date: :asc).all
current_event = all_events.detect { |e| e.start_date.to_date == Time.now.to_date }
index = all_events.index(current_event)
@events = Event.order(start_date: :asc).page(params[:page] || index).per(1)

That might be close enough to work. Note: this approach only works because your LIMIT is 1 i.e. your argument to page.

Upvotes: 0

Related Questions