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;
}

沒有留言: