Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 993
RedRory Avatar asked Oct 27 '11 23:10

RedRory


People also ask

What does ActiveRecord return?

Active Record objects can be created from a hash, a block, or have their attributes manually set after creation. The new method will return a new object while create will return the object and save it to the database. A call to user. save will commit the record to the database.

What is ActiveRecord query?

Active Record insulates you from the need to use SQL in most cases. Active Record will perform queries on the database for you and is compatible with most database systems, including MySQL, MariaDB, PostgreSQL, and SQLite.

Is ActiveRecord ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

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.

like image 56
apneadiving Avatar answered Oct 12 '22 14:10

apneadiving


what you need is

#n=2,3,4 etc    
.limit(1).offset(n) 
like image 26
Sergey Avatar answered Oct 12 '22 13:10

Sergey