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,
2009年2月5日 星期四
2008年8月21日 星期四
update_all
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001308
# Update all billing objects with the 3 different attributes given
Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" )
# Update records that match our conditions
Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" )
# Update records that match our conditions but limit it to 5 ordered by date
Billing.update_all( "author = 'David'", "title LIKE '%Rails%'",
:order => 'created_at', :limit => 5 )
標籤:
rails,
update_all
訂閱:
文章 (Atom)