我有一个属于Product
模型的Client
模型,该模型又属于Debtor
模型。
我需要能够通过Product
和/或Client
搜索Debtor
(我如何使用Ransack进行此操作?)并基于提供Client
和/或Debtor
,我需要根据自定义条件应用一些自定义范围。例如:
Client
,如果scope1
为真,我想申请condition1
。因此Product.search(client: @client)
也会在幕后进行Product.scope1 if condition1
; Client
和Debtor
,如果scope2
为真,我想申请condition2
。因此,Product.search(client: @client, debtor: @debtor)
也会在幕后进行Product.scope2 if condition2
。希望你明白我想要达到的目标。我研究了在模型上定义ransacker
,但不知道如何根据某些条件为结果添加范围。任何帮助将非常感谢!
答案 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