ruby 检查Ransack参数是否为空

5lwkijsr  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(166)

我的控制器中有以下代码

class BooksController < ApplicationController
   expose(:search) { search_books }
   expose(:search_results) { load_results }

   def search_books
      search = Book.ransack(params[:q])
      search.sorts = 'updated_at desc' if search.sorts.empty?
      search
   end

   def load_results
      search.result(distinct: true)
   end
end

在我看来,我有很多的搜索领域设置的各种图书属性,即。title_eqbody_cont
当我单击搜索按钮时,字段为空,Ransack仍然通过q:参数发送参数,即使它们为空。即Parameters: {"utf8"=>"✓", "q"=>{"title_eq"=>"", "book_eq"=>""}等。
我在Ransack里面搜索过,想看看他们是否有一个方法来判断参数是否为空,但我找不到。最好的解决办法是什么?

xwbd5t1u

xwbd5t1u1#

当你可以删除所有的空搜索参数时,你可以调用compact_blank来只返回params中有值的键/值。

params = ActionController::Parameters.new({q: { title: '', body: 'foobar'}})

params[:q].compact_blank
#=> #<ActionController::Parameters {"body"=>"foobar"} permitted: false>

相关问题