问题
How to I retrieve the second, third .. entries in a database. I don't want to use the auto incrementing id generated by rails.
As I am deleting entries from my database, so the ID continues to increase.
So my DB would have
id : 210 (Even thought it's currently the first value)
id : 211 (Even thought it's currently the second value)
I know "Phone.first" will return the first how do I get the second.
Sub Question-
Destroy_all/delete_all -
only removes the item, Can I remove all entries from the DB and have the DB id's start from one without dropping the table. As I ran into problems.
回答1:
Say you want the fourth user:
@users = User.limit(4)
@fourth_user = @users[3]
Concerning your second question, destroy_all should do the trick since it triggers all callbacks. Be sure to add :dependent => :destroy in your relationships.
回答2:
what you need is
#n=2,3,4 etc
.limit(1).offset(n)
回答3:
Model.second was added to Rails 4.1.8.
So you can use it on Rails versions equal to or greater than that.
.third, .fourth and .fifth were also added to ActiveRecord::FinderMethods.
来源:https://stackoverflow.com/questions/7923674/active-record-get-the-second-third-item-in-a-database-without-id