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
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With