如何在Rails中检查(和停止)多删除的空白提交



我有以下代码,可以使用复选框删除多个博客文章,但当用户在没有选择任何博客文章的情况下单击"删除选定的"时,会出现错误。如何确保按钮保持禁用状态或显示未进行选择的弹出错误?为了可视化,以下是我的多重删除的外观(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

只需检查params是否有值,以下是您的操作方法:如何测试rails 中是否存在参数

如果你不喜欢这种方法,你也可以用错误消息来挽救它,但我强烈建议你通过检查param是否有值来完成。

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

最新更新