#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值