0

My goal is to return a single object in a Rails Active Record query. I want to retrieve the most recent record when the table is sorted by the created_at date. So, in the example below, that means I want to return the record with the ID of 2. I don't understand why the 4 queries below all return the same result?

Sales Table Records

 +----+---------+-------+------------+----------------------------+
 | ID | user_id | price | sale_date  |         created_at         |
 +----+---------+-------+------------+----------------------------+
 |  1 |       1 |   200 | 2012-08-07 | 2012-10-02 23:01:46.706727 |
 |  2 |       1 |   400 | 2009-05-11 | 2012-10-02 23:09:01.342879 |
 +----+---------+-------+------------+----------------------------+

Queries:

 <%= current_user.sales.order("created_at").last.price %>

returns: 200

 <%= current_user.sales.order("created_at DESC").last.price %>

returns: 200

 <%= current_user.sales.order("created_at ASC").last.price %>

returns: 200

 <%= current_user.sales.last.price %>

returns: 200

I also tried:

 <%= current_user.sales.last("created_at").price %>

returns: undefined method 'assert_valid_keys' for "created_at":String

2 Answers 2

1

If the Sale class has a default_scope defined, and it includes an order clause, then you may use

.reorder("created_at DESC")

instead of

.order("created_at DESC")
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that was it. I don't know how you guessed that without seeing my model, but nice work!
0

Try this magic incantation if you will:

current_user.sales.sort_by(&:created_at).last

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.