顯示具有 destroy 標籤的文章。 顯示所有文章
顯示具有 destroy 標籤的文章。 顯示所有文章

2009年2月5日 星期四

Activerecord memo (3)

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,

2008年11月13日 星期四

Destroy Without JavaScript

http://railscasts.com/episodes/77-destroy-without-javascript


<!-- projects/index.rhtml -->
<ul>
<% for project in @projects %>
<li>
<%=h project.name %>
<%= link_to_destroy "Destroy", project_path(project), confirm_destroy_project_path(project) %>
</li>
<% end %>
</ul>

<!-- projects/confirm_destroy.rhtml -->
<% form_for :project, :url => project_path(@project), :html => { :method => :delete } do |f| %>
<h2>Are you sure you want to destroy this project?</h2>
<p>
<%= submit_tag "Destroy" %>
or <%= link_to "cancel", projects_path %>
</p>
<% end %>


# routes.rb
map.resources :projects, :member => { :confirm_destroy => :get }

# projects_controller.rb
def confirm_destroy
@project = Project.find(params[:id])
end

# projects_helper.rb
def link_to_destroy(name, url, fallback_url)
link_to_function name, "confirm_destroy(this, '#{url}')", :href => fallback_url
end


/* application.js */
function confirm_destroy(element, action) {
if (confirm("Are you sure?")) {
var f = document.createElement('form');
f.style.display = 'none';
element.parentNode.appendChild(f);
f.method = 'POST';
f.action = action;
var m = document.createElement('input');
m.setAttribute('type', 'hidden');
m.setAttribute('name', '_method');
m.setAttribute('value', 'delete');
f.appendChild(m);
f.submit();
}
return false;
}