I am making a board which consists of “post” model and “comment” model.
The board I’m making doesn’t need signing-in procedure, so the password is needed for a deletion of a post or a comment.
When I am trying to delete a post, the code below works well.
(If a user click the “Delete” button, the hidden DIV which has a password form appears, so I used form_for.)
<%= link_to_function "Delete", "$('#post_password_box').toggle()" %> |
<div id="post_password_box">
<%= form_for(@post, url: { action: "destroy"}, html: { method: :delete, class: nil, id: nil}) do |f| %>
<%= f.label :password %>
<%= f.password_field :password %><br>
<%= f.submit "Commit", class: "btn", data: { confirm: "Are you sure?" } %>
<%= button_to_function "Cancel", "$('#post_password_box').hide()", class: "btn" %>
<% end %>
</div>
So, I used the similar code when it comes to delete the comment.
<% @comments.each do |comment| %>
<li class="author"><%= comment.author %></li>
<li class="content"><%= comment.content %></li>
<li class="date"><%= comment.created_at.localtime.strftime("%r") %></li>
<li class="button">
<%= link_to_function "X", "$(this).next().toggle()" %>
<div class="comment_password_box">
<%= form_for(comment, url: {controller: "comments", action: "destroy"}, html: {method: :delete, class: nil, id: nil}) do |f| %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit %>
<% end %>
</div>
</li>
<% end %>
At a glance, The code above seems to work well, but there is a problem that the code doesn’t delete a proper comment.
For example, if the id of a post is 20 and the id of a comment I want to delete is 10, it deletes the comment whose id is 20.
And I found the problem comes from the fact that the form tag’s action attributes is like below in every comment.
<form accept-charset="UTF-8" action="/comments/20" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="_method" type="hidden" value="delete" /><input name="authenticity_token" type="hidden" value="Y2oBuoIxa+9yPLC5WflKVVELw3jgKsi9s9/8Cfvr2u8=" /></div>
What should I do to make rails find the proper form tag’s action attribute’s value? (In this case, it should be “/comments/10”, instead of “/comments/20”.)
Let rails generate the URL for you. At the moment you’re setting the URL yourself but you’re not specifying a value for
:idso rails takes the current value ofparams[:id]Try
Instead.