Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ActiveRecord's finder methods: take vs limit(1)

Considering the following finder methods of ActiveRecord.

  • .take. Example. Account.take
  • .limit(1) Example. Account.limit(1)

Now, both methods althought have different names but they generate the same query:

SELECT "accounts".* FROM "accounts" LIMIT 1

So, what is the difference between .take & .limit(1)? or they are the same?

like image 257
CuriousMind Avatar asked Oct 01 '13 18:10

CuriousMind


People also ask

What does .take do in Rails?

take Gives a record (or N records if a parameter is supplied) without any implied order. The order will depend on the database implementation.

What is an active record relation?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

From the docs

# File activerecord/lib/active_record/relation/finder_methods.rb, line 64
def take(limit = nil)
  limit ? limit(limit).to_a : find_take 
end

take returns an Array of records while limit returns an ActiveRecord Relation that can be chained with other relations.

like image 112
tihom Avatar answered Oct 17 '22 12:10

tihom