Ransack:如何使用现有范围?

Geo*_*ann 14 ruby-on-rails arel ruby-on-rails-3 ransack

将Rails 2应用程序转换为Rails 3,我必须替换gem searchlogic.现在,使用Rails 3.2.8和gem Ransack我想构建一个使用现有范围的搜索表单.例:

class Post < ActiveRecord::Base
  scope :year, lambda { |year| 
    where("posts.date BETWEEN '#{year}-01-01' AND '#{year}-12-31'") 
  }
end  
Run Code Online (Sandbox Code Playgroud)

据我所知,这可以通过定义自定义搜索来实现.可悲的是,我没有找到任何关于此的文档.我在Post课堂上尝试过这个:

ransacker :year, 
          :formatter => proc {|v| 
            year(v)
          }
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

Post.ransack(:year_eq => 2012).result.to_sql
=> TypeError: Cannot visit ActiveRecord::Relation
Run Code Online (Sandbox Code Playgroud)

我尝试了ransacker声明的一些变体,但它们都不起作用.我需要一些帮助...

更新:上面的范围只是示例.我正在寻找一种方法来使用Ransack中的每个现有范围.在Ransack的前身MetaSearch中,有一个要求search_methods使用范围的功能.Ransack 尚未支持此开箱即用.

Fiv*_*ell 8

合并https://github.com/activerecord-hackery/ransack/pull/390后,ransack可以立即使用它。您应该声明ransakable_scopes方法以添加对ransack可见的范围。

从手册

从上一节继续,按作用域搜索需要在模型类上定义ransackable_scopes白名单。白名单应该是符号数组。默认情况下,所有类方法(例如,范围)都将被忽略。范围将应用于匹配真实值,如果范围接受一个值,则将应用于给定值:

class Employee < ActiveRecord::Base
  scope :activated, ->(boolean = true) { where(active: boolean) }
  scope :salary_gt, ->(amount) { where('salary > ?', amount) }

  # Scopes are just syntactical sugar for class methods, which may also be used:

  def self.hired_since(date)
    where('start_date >= ?', date)
  end

  private

  def self.ransackable_scopes(auth_object = nil)
    if auth_object.try(:admin?)
      # allow admin users access to all three methods
      %i(activated hired_since salary_gt)
    else
      # allow other users to search on `activated` and `hired_since` only
      %i(activated hired_since)
    end
  end
end

Employee.ransack({ activated: true, hired_since: '2013-01-01' })

Employee.ransack({ salary_gt: 100_000 }, { auth_object: current_user })
Run Code Online (Sandbox Code Playgroud)


Nov*_*vae 1

Ransack 让您为此创建自定义谓词,不幸的是,文档留有改进的空间,但是结账: https: //github.com/ernie/ransack/wiki/Custom-Predicates

另外,我相信您要解决的问题已在他们的问题跟踪器上。那里正在进行很好的讨论:https://github.com/ernie/ransack/issues/34