Bruno Amaral
Bruno Amaral

Reputation: 169

Sorting local variable

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.

  1. the following methods have not worked: sort, sort_by, order
  2. 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"> 
    

Upvotes: 1

Views: 217

Answers (2)

InternetSeriousBusiness
InternetSeriousBusiness

Reputation: 2635

@audit = Audit.where( "auditable_id IN (?) OR auditable_id IN (?)",
                       current_user.posts,
                       @comments ).order_by( :created_at )

Upvotes: 0

georgebrock
georgebrock

Reputation: 30043

You should be able to build a single query to load all of the Audit objects 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:

SELECT *
FROM audits
WHERE
  auditable_type = 'Post' AND auditable_id = … OR
  auditable_type = 'Comment' AND auditable_id IN (…)
ORDER BY created_at

Which you should be able to build using Arel with something like this (assuming you're using Rails 3):

t = Audit.arel_table
for_post = t[:auditable_type].eq('Post').and(t[:auditable_id].eq(post.id))
for_comments = t[:auditable_type].eq('Comment').and(t[:auditable_id].in(comment_ids))

audits = Audit.where(for_post.or(for_comments)).order(:created_at)

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_sql or pass a string to where, but bear in mind that using Arel will shield you from various kinds of errors and subtle difference between databases.

Upvotes: 1

Related Questions