In Ruby on Rails, what's the difference betwee

2020-02-05 07:38发布

问题:

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...

回答1:

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



回答2:

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)>


回答3:

Yes. An exception is raised if the record is invalid.