Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find a single record using ActiveRecord 3 / Arel?

Where I used to do this:

Foo.find_by_bar('a-value') 

I can now do this:

Foo.where(:bar => 'a-value').limit(1).first 

Is this recommended? Is this the best way? Should I continue to use the "old" way because it continues to be useful syntactic sugar, or is there an Even Better way I can do that now, which will support chaining and all the other good stuff?

like image 615
John Bachir Avatar asked Jun 13 '11 03:06

John Bachir


People also ask

What are ActiveRecord methods?

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format, and many more.

Is ActiveRecord an 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.

What is ActiveRecord relation?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

Rails 4 :

Foo.find_by bar: 'a_value' , wibble: 'a wibble value' 
like image 133
SureshCS Avatar answered Oct 17 '22 07:10

SureshCS