Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Query all but first record?

How would I query all except the first record using ActiveRecord?

Something like...

Item.where(:widget_id => 123).all_but_first

I'm running Rails 3.2.

like image 681
Shpigford Avatar asked Mar 08 '12 20:03

Shpigford


People also ask

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? 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.

What is eager loading in rails?

Eager loading is a way to find objects of a certain class and a number of named associations. Here I share my thoughts on using it with Rails. What are N + 1 queries? It mainly occurs when you load the bunch of objects and then for each object you make one more query to find associated object.

What is ActiveRecord relation?

Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet). Once you run that query by calling to_a , each , first etc. on that Relation a single instance or an array of ActiveRecord::Base instances will be returned.

What is ORM in Ruby on Rails?

Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.


2 Answers

I'd do it like this:

Item.where(:widget_id => 123).all[1..-1]
like image 109
Veraticus Avatar answered Sep 25 '22 10:09

Veraticus


Alternatively you could use offset and limit with a very high limit.

Item.where(:widget_id => 123).limit(18446744073709551610).offset(1)

see Mysql Offset Infinite rows for a discussion on this.

like image 21
Volker Pacher Avatar answered Sep 22 '22 10:09

Volker Pacher