Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rails find_or_initialize_by_email, how to determine if record if found or initialized?

In one of my controllers, I'm doing:

user = User.find_or_initialize_by_email(@omniauth['info']['email'])

I then need to know if the records was found or initialized. I had tried this:

if user
else
end 

But that does not work as there will always be a user. What is the right way to know if find or initialize found or initialized?

Thanks

like image 200
AnApprentice Avatar asked Aug 10 '13 17:08

AnApprentice


People also ask

What is an active record in rails?

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

What is an active record 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.


Video Answer


2 Answers

You should be able to use persisted?:

if user.persisted?

edgeguides.rubyonrails.org says the following about find_or_initialize_by:

The find_or_initialize_by method will work just like find_or_create_by but it will call new instead of create. This means that a new model instance will be created in memory but won't be saved to the database.

like image 85
pdoherty926 Avatar answered Oct 23 '22 00:10

pdoherty926


An alternative to @pdoherty926's answer is to use the new_record? method.

if user.new_record?

It would return the opposite truthy value from persisted? though, so you have a choice on which works for your conditional logic. (I tend to find if to be more readable than unless sometimes, for example.)

like image 31
Chris Peters Avatar answered Oct 23 '22 00:10

Chris Peters