I’d like to create a method second_to_last that is similar to last but returns the second to last record from a model instead of the last record. I thought this would be trivial since the SQL for last is:
Select * from "users".* FROM "Users" ORDERED BY "ORDERED BY" "users"."id" DECS LIMIT 1
I have to find a way to change the Limit 1 to Limit 2 and then select the first element. Am I thinking correctly? Is there a better approach?
I think you were on the right track. Try something like this:
This should return the second-to-last record.
There are even ways to extend Rails with your new method but that is probably beyond the scope of your question.
Even better, you can use User.last(2). I dosen’t get much simpler than that.