#77 Destroy Without JavaScript

If the user has JavaScript disabled, the "Destroy" link might not work properly. In this episode I will explore a number of ways to work around this issue.
<!-- 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;
}

你可能感兴趣的:(JavaScript,html,F#)