Active Record - Get the second, third.. item in a database (without ID)

邮差的信 提交于 2019-12-18 14:37:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!