AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

How to get .last object according to .id?

I have in my view duel.duelers.last, which is suppose to grab the dueler with the last id in the duel, but instead if a dueler updates an attribute then that dueler becomes last regardless of its order in id?

How can I grab the last dueler based on id?

pry(main)> Duel.last.duelers
=> [#<Dueler:0x007fa718513530
  id: 310, # This is Duel.last.duelers.last but is listed first here
  user_id: 2,
  challenge_id: 398,
  duel_id: 186,
 #<Dueler:0x007fa718513288
  id: 309, # This is Duel.last.duelers.first but is listed last here because it was most recently updated
  user_id: 114, 
  challenge_id: 410,
  duel_id: 186,
pry(main)> Duel.last.duelers.last
 id: 310,
 user_id: 2,
 challenge_id: 398,
 duel_id: 186,
pry(main)> Duel.last.duelers.first
 id: 309,
 user_id: 114,
 challenge_id: 410,
 duel_id: 186,

Upvotes: 0

Views: 99

Answers (2)

Sravan
Sravan

Reputation: 18657

you want to grab the last dueler based on id,

No matter what column you update last in your table, the basic query will be ordered by duelers_id desc

Rails default order:

In rails if there is no order specified by default, so they will be ordered by how the database returns them. Usually this is by ID or insert order. The created_at/updated_at column is only there if you specify it in your migrations so it wouldn't make sense for that to be the default order column.

Here is an example query I made for you.

Duel.last.duelers.last

Duel Load (0.5ms)  SELECT  `duels`.* FROM `duels`  ORDER BY `duels`.`id` DESC LIMIT 1

Dueler Load (37.3ms)  SELECT `duelers`.* FROM `duelers` WHERE `duelers`.`duel_id` = 1 ORDER BY `duelers`.`id` DESC LIMIT 1

This query first loads the respective Duel and then gets the last dueler of that duel order by dueler_id desc.

Check the query,

SELECTduelers.* FROMduelersWHEREduelers.duel_id= 1 ORDER BYduelers.idDESC LIMIT 1

it always order by id desc unless you give a default scope.

In your question, it is getting the results in the correct order which is the descending order of Id

Upvotes: 2

AnkurVyas
AnkurVyas

Reputation: 259

You can try

Duel.last.duelers.order(id: :desc).first

Or

Duel.last.duelers.order(created_at: :desc).first

Hope this helps!

Upvotes: 1

Related Questions