ActiveRecord::Base
save, save!, create, create!, update_attribute, update_attributes, update, update_all, delete, delete_all, destroy, destroy_all
1. save vs save!
save 成功 => true
save 失敗 => fasle
另外 save(perform_validation = true), save 還可以丟個參數進去, save(false) 的話, 一堆validate 都不跑, 可是會跑before_*, 失敗一樣是return false
save! 成功 => true
save! 失敗 => validate 失敗:RecordInvalid execption,
before_* 失敗 : RecordNotSaved
2. create vs create!
create 成功 => ActiveRecord object
create 失敗 => ActiveRecord object, 所以要確認成功失敗可以用 errors.empty? 檢查
create! 成功 => ActiveRecord object
create! 失敗 => RecordInvalid
3. 如果是資料庫的validate 就會爆 StatementInvalid
例如有這樣的設定 t.column :user_id, :integer, :null => false
沒填user_id 就會爆StatementInvalid
4. update_attribute vs update_attributes
除了可以更新update的多寡之外,
還有 update_attribute 是 save(false), 它不跑 validate
同樣成功true, 失敗false
5 update, update_all
丟的參數差很多
update(id, attributes)
update_all(updates, conditions = nil, options = {})
6.delete_all, delete, destroy, destroy_all
delete 是不會跑before_, after_ destroy 還有 dependent 也是不跑的
destroy_all(conditions = nil)
delete_all(conditions = nil)
7. ConnectionAdapters::DatabaseStatements
connection.select_all
8. ActiveRecord::ConnectionAdapters::AbstractAdapter
ActiveRecord::Base.connection returns an AbstractAdapter object,
沒有留言:
張貼留言