0

I have following code which delete multiple blogposts using checkboxes but when the user clicks on the "Delete Selected" without selecting any blogpost, it gives error. How to make sure the button stays disable or shows a popup error that no selection has been made ? To visualize, here is how my multi delete looks (https://i.stack.imgur.com/P80OG.png)

routes.rb:

  resources :blog_posts do
    collection do
      delete 'destroy_multiple'
    end
  end

index.html.erb:

<%= form_tag destroy_multiple_blog_posts_path, method: :delete do %>
<table>
...
<td><%= check_box_tag "blog_posts[]", blog_post.id %></td>
...
</table>
<%= submit_tag "Delete selected" %>
<% end %>

blog_posts_controller.rb:

def destroy_multiple

  BlogPost.destroy(params[:blog_posts])

  respond_to do |format|
    format.html { redirect_to blog_posts_path }
    format.json { head :no_content }
  end

end
iCyborg
  • 4,699
  • 15
  • 53
  • 84

1 Answers1

1

Just check if the params has a value, here is how you do that: How to test if parameters exist in rails

If you don't like that approach you can also rescue it with an error message, but I highly recommend that you do it by checking if the param has values.

begin
    BlogPost.destroy(params[:blog_posts])
rescue
     #this will fire if begin block throws an error, so just throw your error at the user here
ensure
    #this_code_is_always_executed, if you want to ensure something happens no matter what
end
Community
  • 1
  • 1
Bagzli
  • 6,254
  • 17
  • 80
  • 163