0

I have a model which I am filtering based on some parameters given by the user. The filtering works just fine but once I start using pagination, only the records from the first page are filtered and the others are ignored. This is my code in the controller for filtering:

 @start_date = params[:start_date]
 @registers = Register.all.order("payment_date DESC").page(params[:page]).per(params[:all] ? nil : Kaminari.config.default_per_page)
 @registers.delete_if { |r| !(r.payment_date <= @end_date && r.payment_date >= @start_date) if (@start_date.present? && @end_date.present?) }

And in the view I use <%= paginate @registers %> to paginate the list.

Kupi
  • 903
  • 1
  • 10
  • 16
  • When you click on the second page, you can see the end_date and start_date params in the URL, right? Kaminari passes them automatically? – Peter Haight May 27 '16 at 06:49
  • Note that the date filtering will not work together with pagination like that. You should describe the data set as a query including all conditions and THEN paginate on that. E.g. `Register.where('payment_date <= ? AND payment_date >= ?', @end_date, @start_date).order(...).page(...).per_page(...)` – Raffael May 27 '16 at 06:53
  • How many pages should there be according to the number of records in the database? – Raffael May 27 '16 at 06:54
  • @PeterHaight the params are passed to the second page yes. But if the first page doesn't contain any records that are filtered by the dates, it's just empty and the second page is not.. – Kupi May 27 '16 at 07:03
  • @Raffael I am using the "delete_if" because there are other params on which I am filtering but they could also be empty that's why I'm not using "where" – Kupi May 27 '16 at 07:06
  • 1
    Then construct your query step by step. `@r = Register.all`; `@r = @r.where(...) if ...`; `@r = @r.order(...).page(...).per_page(...)`. Using delete_if will screw up your page numbers. – Raffael May 27 '16 at 07:09
  • Aight thanks man this worked. If you post it in an answer I can markt it :D – Kupi May 27 '16 at 07:37

1 Answers1

0

Like @Raffael mentioned in a comment above, I had to use @registers = @registers.where(..) instead of @registers.delete_if(..) because it "screws your page numbers up".

Kupi
  • 903
  • 1
  • 10
  • 16