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

久未见 提交于 2020-01-09 10:24:53

问题


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.



来源:https://stackoverflow.com/questions/5010325/in-ruby-on-rails-whats-the-difference-between-create-and-create-and-api-docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!