Lakhan
Lakhan

Reputation: 185

Rails, how to sort the array of active records by created_at

Hi there I have two arrays having different values of active records from same table but having different values, I want to combine them both and then sort them by created_at, but not getting any clue, I am stuck. Please help.

Here is my code:

@find_user = EmployeeLeave.where(global_user_id: @allarray[i]).find(:all)
@all << @find_user
@find_referal_user = EmployeeLeave.where(referral_id: @allarray[i]).find(:all)
@all_entry << @find_referal_user
@total = @all + @all_entry

any thing is not working please help me to sort the @total.

Upvotes: 18

Views: 25464

Answers (4)

Nezir
Nezir

Reputation: 6915

And if you need descending order just use reverse

@total.sort_by(&:created_at).reverse

Upvotes: 6

josetapadas
josetapadas

Reputation: 2637

You can always use the order method:

@total.order! 'created_at DESC'

Upvotes: 7

Yevgeniy Anfilofyev
Yevgeniy Anfilofyev

Reputation: 4847

You could do it in this way:

@total = EmployeeLeave.find(
  :all,
  :conditions => ["global_user_id = ? or referral_id = ?", @allarray[i], @allarray[i]],
  :order => "created_at ASC"
)

So it will find all EmployeeLeave whose global_user_id or referral_id eq @allarray[i] and sort the result by created_at.

Upvotes: 0

Peter de Ridder
Peter de Ridder

Reputation: 2399

You can sort an array by using sort_by.

In your case, you could do the following:

@total.sort_by(&:created_at)

Update:

  • Remove @all << @find_user and @all_entry << @find_referal_user
    • Why? Because otherwise you will have an array with multiple arrays
  • Replace @total with: @total = @find_user + @find_referal_user
    • Why? Because @total will now only consists of one merged array with all objects, ready to get sorted through .sort_by(&:created_at).

Upvotes: 38

Related Questions