My Rails app is getting the history of changes for two models, using the auditor gem like so:
@audit = Audit.where( :auditable_id => current_user.posts,
:auditable_type => "Post") +
Audit.where( :auditable_id => @comments,
:auditable_type => "Comment")
This works, but then I need to sort the whole @audit variable by the time the change was made.
I have two issues to solve.
- the following methods have not worked:
sort,sort_by,order -
I need to figure out which of the following fields I need to sort by:
=> Audit(id: integer, auditable_id: integer, auditable_type: string, owner_id: integer, owner_type: string, user_id: integer, user_type: string, action: string, audited_changes: text, version: integer, comment: text, **created_at**: datetime) 1.9.3-p194 :002 > Audit.last Audit Load (168.0ms) SELECT "audits".* FROM "audits" ORDER BY version DESC, created_at DESC LIMIT 1 => #<Audit id: 5, auditable_id: 58, auditable_type: "Post", owner_id: 58, owner_type: "Post", user_id: 1, user_type: "User", action: "update", audited_changes: {"status"=>["to approve", "to review"], " **updated_at** "=>[2012-08-24 15:29:26 UTC, 2012-08-24 19:29:52 UTC]}, version: 2, comment: "post modified by Bruno Amaral ", created_at : "2012-08-24 19:29:52">
You should be able to build a single query to load all of the
Auditobjects you’re interested in. Since it’s a single query, the database can handle the sorting too.The SQL you want to execute looks something like this:
Which you should be able to build using Arel with something like this (assuming you’re using Rails 3):
For more information about building complex queries with Arel, see ASCIIcasts episode 215 and the Arel README.
If you don’t like the Arel syntax, you can also use
find_by_sqlor pass a string towhere, but bear in mind that using Arel will shield you from various kinds of errors and subtle difference between databases.