Reputation: 5392
I have an app (a tutorial) which has Articles and Comments. An Article has_many Comments. A Comment belongs_to an Article. I'm having a problem deleting an Article's Comment. Here are the files in question:
app/views/comments/_comment.html.erb
<%= div_for comment do %>
<h3>
<%= comment.name %> <<%= comment.email %>> said:
<span class='actions'>
<%= link_to 'Delete', [@article, comment], confirm: 'Are you sure?', method: :delete %>
</span>
</h3>
<%= comment.body %>
<% end %>
CommentsController
before_filter :load_article
def create
@comment = @article.comments.new(params[:comment])
if @comment.save
redirect_to @article, :notice => 'Thanks for your comment'
else
redirect_to @article, :alert => 'Unable to add comment'
end
end
def destroy
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to @article, :notice => 'Comment deleted'
end
private
def load_article
@article = Article.find(params[:article_id])
end
routes.rb
resources :articles do
resources :comments
end
The problem is when I'm at address localhost:3000/articles/1 and try to delete a comment. Instead of being redirected to the Article show action I get this error at address localhost:3000/articles/1/comments/3:
Unknown action
The action 'show' could not be found for CommentsController
any help greatly appreciated, thanks, mike
Upvotes: 0
Views: 101
Reputation: 4237
You have two basic options here, because a link in most browsers can only send a GET request.
First option is to include the java-script default files into the page
<%= javascript_include_tag :defaults %> #this mocks a delete action by modifying the request automatically
Second and much preferable is to use button_to instead. First, there is a logical separation between a link to a place and a button to do something. Delete is definitely an action. Further, buttons aren't followed by spiders so nothing ever gets accidentally called.
<%= button_to 'delete', @comment, :method => :delete %>
========= EDIT FOR COMPLETENESS ======= If you are worried about the links and buttons not looking the same, an easy solution is to us jquery/jquery_ui to style all links and buttons exactly the same.
Upvotes: 1