`
hideto
  • 浏览: 2678096 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Rails宝典七十七式:禁止JavaScript时的Destroy

    博客分类:
  • Ruby
阅读更多
Rails里一般我们这样Destroy:
<%= link_to "Destroy", project_path(project), :confirm => "Are you sure?", :method => :delete %>

但是当客户端浏览器禁止JavaScript时就呆了,没有confirm,直接给删除了
所以如果我们需要考虑这种情况的话,需要给出“可降级”的方案,例如跳转到另一个页面,页面上提示是删除or取消
最终是这样来用:
<!-- 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>

link_to_destroy是自定义的一个helper,第一个参数为link名,第二个参数为允许JavaScript时的link,第三个参数为禁止JavaScript时的link
# projects_helper.rb
def link_to_destroy(name, url, fallback_url)
  link_to_function name, "confirm_destroy(this, '#{url}')", :href => fallback_url
end

实际上link_to_destroy调用了link_to_function,其所调用的JavaScript方法为confirm_destroy:
/* 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;
}

confirm_destroy方法很眼熟吧?对,就是通常我们写Destroy链接时Rails所生成的JavaScript
这里我们的fallback_url为confirm_destroy_project_path:
# routes.rb
map.resources :projects, :member => { :confirm_destroy => :get }

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

<!-- 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 %>


很完美的方案!
但是看看这个episode的comment也很搞笑:
引用

HappyCoder   Oct 29, 2007 at 02:23
If a user doesn't have js enabled, then f*ck him.
分享到:
评论
1 楼 xu_ch 2009-06-24  
 

相关推荐

Global site tag (gtag.js) - Google Analytics