Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby on Rails, what's the difference between create and create! and API docs doesn't have it?

ActiveRecord has create and some people use create!... Is it that create! can raise an exception while create doesn't? I can't find create! in the current Rails API docs...

like image 246
nonopolarity Avatar asked Feb 15 '11 22:02

nonopolarity


2 Answers

Yes, create! will raise an exception on failure, create just returns false. Documentation here:

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-create-21

like image 181
cam Avatar answered Oct 02 '22 01:10

cam


I have tested it in Rails 4.2.0. In this version of Rails, it seems, #create! works as said in the other answer, but not the #create method.

#create

creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

Here is some try as per the documentation.

Arup-iMac:rails_app_test shreyas$ rails c
Loading development environment (Rails 4.2.0)
[1] pry(main)> show-models Person
Person
  id: integer
  name: string
  created_at: datetime
  updated_at: datetime
[2] pry(main)> Person.create!
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank, Name is too short (minimum is 3 characters)
from /Users/shreyas/.rvm/gems/ruby-2.1.5@rails_app_test/gems/activerecord-4.2.0/lib/active_record/validations.rb:79:in `raise_record_invalid'
[3] pry(main)> Person.create
   (0.1ms)  begin transaction
   (0.0ms)  rollback transaction
=> #<Person:0x007fdb4cc5b0a0 id: nil, name: nil, created_at: nil, updated_at: nil>
[4] pry(main)> Person.count
   (0.2ms)  SELECT COUNT(*) FROM "people"
=> 0
[5] pry(main)>
like image 44
Arup Rakshit Avatar answered Oct 02 '22 01:10

Arup Rakshit