削除リンク
Railsでレコード削除のときのリンクってどう書くんだっけと迷ったのでメモ。
正解
<%= link_to '削除', @org, :method=>:delete, :confirm=>'よろしいですか?' %>
HTMLに展開されるとこんな複雑怪奇なものになります。(見やすいように改行が入れてあります)
<a href="/organizations/2" onclick= "if (confirm('よろしいですか?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href; var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m); var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', '02cae46eb8c1342f848c7aad341e5074e68f68ee'); f.appendChild(s); f.submit(); }; return false;" >削除</a>
不正解
<%= link_to '削除', destroy_organization_path %> NameError Exception: undefined local variable or method <%= link_to '削除', {:action=>'destroy', :id=>@org.id, :method=>:post} %> <a href=\"/org/2?method=post\">削除</a> <%= link_to '削除', {:action=>'destroy', :method=>:post} %> <a href=\"/org/2?method=post\">削除</a> <%= link_to '削除', organization_path + '/destroy' %> <a href=\"/org/2/destroy\">削除</a>
おまけ
<%= link_to '削除', @org, :method=>:delete, :confirm=>'削除します。\nよろしいですか?' %>
これでは確認メッセージが改行されない。どこを疑うべきか。\nを\\nにすべきだったか?
否、シングルクォート ⇒ ダブルクォート