mardi 22 décembre 2015

Rails "hidden" rows counting toward pagination count

I have a rails site that allows users to register for sessions. This list tries to filter out spaces where there are available slots and only displays an unregister button to the users that have already registered. The problem I have is that it only shows my per page count less the number of records that are hidden. For instance, 30 sessions are full but there are 50 per page, it shows 20 sessions. There is a varying limit of space per session, which must be checked (called attendee_limit).

I am using the code below. If I could easily page by one of my fields (start_date) or show a total of 50 per page as normal, I'd be happy. I cut out the majority of the view code but included the if statement to determine if it should be displayed. I figure I need to do this controller side to filter out those results entirely, but can't think of a good way to approach it due to the need to still allow users to unregister. Any idea of how I can accomplish this without just ditching pagination?

Helper methods

def registered(course_session, user)
  attendee = Attendee.where("user_id = ? and course_session_id = ?",
    user.id, course_session.id).first
  return attendee
end

def open_slots(course_session)
  attendees = Attendee.where(:session_id => course_session.id).count
  return course_session.attendee_limit - attendees
end

View

<% @course_sessions.each do |course_session| %>
<% 
  isreg = registered(course_session, current_user)
  if isreg || (open_slots(course_session) > 0) %>
    <!-- Display index -->
<% end %>
<% end %>
<%= will_paginate @course_sessions %>

Controller

def index
  @course_sessions = CourseSession.joins(:room).order("starts_at")
   .page(params[:starts_at]).per_page(50)
  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @course_sessions }
end

end

Aucun commentaire:

Enregistrer un commentaire