将自定义范围与Ransack一起使用

时间:2015-02-06 14:58:01

标签: ruby-on-rails ruby scope ransack

我有一个属于Product模型的Client模型,该模型又属于Debtor模型。

我需要能够通过Product和/或Client搜索Debtor(我如何使用Ransack进行此操作?)并基于提供Client和/或Debtor,我需要根据自定义条件应用一些自定义范围。例如:

  • 如果我提供Client,如果scope1为真,我想申请condition1。因此Product.search(client: @client)也会在幕后进行Product.scope1 if condition1;
  • 如果我同时提供ClientDebtor,如果scope2为真,我想申请condition2。因此,Product.search(client: @client, debtor: @debtor)也会在幕后进行Product.scope2 if condition2

希望你明白我想要达到的目标。我研究了在模型上定义ransacker,但不知道如何根据某些条件为结果添加范围。任何帮助将非常感谢!

1 个答案:

答案 0 :(得分:2)

由于缺乏信息,无法为您的应用编写工作代码。

但有时候,我需要在某个范围内过滤搜索结果,可选择在表单中检查时,例如

我以这种方式使用自定义范围的搜索者:

在app / ransackers / custom_ransacker.rb

class CustomRansacker < BaseRansacker
  # value param - is passed from form, it can be string, integer, boolean, what ever.
  # you can use it, to decide which scope to apply, for example
  def eq(value)
    table[:id].in(model_ids)
  end

  def model_ids
    MyModel.my_scope.map(&:id)
  end
end

应用程序/ ransackers / base_ransacker.rb:

class BaseRansacker
  attr_reader :table

  # @param [Arel::Table] table
  def initialize(table)
    @table = table
  end

  def self.call(parent)
    new(parent.table)
  end
end

应用程序/模型/ my_model.rb

class MyModel < AR::Base
  scope :my_scope, ->{ # some conditions }

  ransacker :some_field_name, callable: CustomRansacker
end