Sunday, 3 April 2016

Difference between create and save in Ruby on Rails




Create is a class Method where as Save is an instance method, but both method belongs to Active Record::Base class.

If successfully validated, Create method creates an object (or multiple objects) and saves it to the database.The resulting object is returned whether the object was saved successfully to the database or not.

The parameters can either be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created

for ex- User.create(:firstname => “Jyoti Ranjan”)

From the above example, you can know that Create is a class method.
While in Save, If the model is new, a record gets created in the database, otherwise the existing record gets updated.

If the performed validation is true validations, then the save method will return true and save the content in the database. If any of them fail, the action is canceled and save returns false.

For ex- @user.save

From the above example, you can see that Save is an instance method.

No comments:

Post a Comment