Default sort versions with papertrail
Asked Answered
A

4

6

I'm using the paper_trail gem in my Rails 4 application and I want to set a default sort order. papertrail doesn't have a model, only a controller and an initializer.

Where can I put it? Do I have to create a model for it?

default_scope order('created_at DESC')
Ardene answered 23/4, 2014 at 17:52 Comment(0)
A
8

Well I found that I could just use reverse in my each do block.

versions.reverse.each

Since I need nothing more complex than that I guess it will do for now.

Ardene answered 24/4, 2014 at 12:17 Comment(3)
If you only have small number of versions this still works, but for larger amounts will be very bad for performance.Furfural
I'm also using limit to only get the latest 10 or so versions, and this method won't work because paper_trail seems to sort by created_at ASC by default.Bookmark
This doesn't work with pagination. Dave T' answer does. versions.reorder(created_at: :desc)Pappas
K
9

There's also the reorder command.

http://apidock.com/rails/ActiveRecord/QueryMethods/reorder

versions.reorder('created_at DESC')

It will replace any prior ordering, thus ignoring Papertrail's pre-defined order.

Kitchenware answered 5/9, 2016 at 7:2 Comment(0)
A
8

Well I found that I could just use reverse in my each do block.

versions.reverse.each

Since I need nothing more complex than that I guess it will do for now.

Ardene answered 24/4, 2014 at 12:17 Comment(3)
If you only have small number of versions this still works, but for larger amounts will be very bad for performance.Furfural
I'm also using limit to only get the latest 10 or so versions, and this method won't work because paper_trail seems to sort by created_at ASC by default.Bookmark
This doesn't work with pagination. Dave T' answer does. versions.reorder(created_at: :desc)Pappas
F
4

The correct way would be to remove the previous sorting via unscope and then set it however you want:

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-unscope

For example:

somethings.version.merge(PaperTrail::Version.unscope(:order)).order('created_at DESC')

This would give you a proper Query with the right sorting

Furfural answered 1/11, 2014 at 20:5 Comment(1)
Interesting. I didn't know about unscope. I will try this out. Thanks.Ardene
K
-1

find version.rb in paper_trail gem. directory on my computer shown below. add:

scope :by_date_desc, lambda { unscope(:order).order('created_at DESC') }

unscope necessary to remove prior order in chain (thank you maxigs). use your favorite scope name of course. worked for me.

C:\Ruby200\lib\ruby\gems\2.0.0\gems\paper_trail-4.0.0.beta2\lib\paper_trail\frameworks\active_record\models\paper_trail\version.rb

Knightly answered 27/2, 2015 at 19:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.