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

时间:2013-08-22 11:40:28

标签: ruby-on-rails ruby-on-rails-3

我有以下代码,使用复选框删除多个博客帖子但是当用户点击“删除所选项目”而不选择任何博客帖子时,它会出错。如何确保按钮保持禁用状态或显示弹出错误,表明没有选择?要进行可视化,以下是我的多重删除外观(http://i.imgur.com/3mfglyI.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

1 个答案:

答案 0 :(得分:1)

只需检查params是否有值,以下是您的操作方法:How to test if parameters exist in rails

如果您不喜欢这种方法,您也可以使用错误消息来解救它,但我强烈建议您通过检查参数是否具有值来执行此操作。

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