Filter rails ActiveAdmin中使用ransack的自定义过滤器
我已经创建了一个activeadmin过滤器,它在下拉菜单中有以下关于过滤表数据的选项 选择A 选择B 选择C 选择D 我想添加第五个选项F,即选项B或C(即B和C的结果) 选择A 选择B 选择C 选择D 选择F=B或C 这些选项存储在标题字段中名为优惠券的表中(我创建了一行,其中包含选项F)。到目前为止,我还没有完全确定,就试图用搜身来做这件事Filter rails ActiveAdmin中使用ransack的自定义过滤器,filter,activeadmin,ransack,Filter,Activeadmin,Ransack,我已经创建了一个activeadmin过滤器,它在下拉菜单中有以下关于过滤表数据的选项 选择A 选择B 选择C 选择D 我想添加第五个选项F,即选项B或C(即B和C的结果) 选择A 选择B 选择C 选择D 选择F=B或C 这些选项存储在标题字段中名为优惠券的表中(我创建了一行,其中包含选项F)。到目前为止,我还没有完全确定,就试图用搜身来做这件事 //app/admin/user.rb filter :has_right_choice, label: 'Filter by the right c
//app/admin/user.rb
filter :has_right_choice, label: 'Filter by the right choice', collection: Coupon.all, as: :select
//app/models/user.rb
ransacker :has_right_choice, :formatter => ->(title) {
if (title == 'Choice F')
Coupon.all.where("title = 'Choice B' OR title = 'Choice C'")
else
Coupon.all
end
} do |parent|
parent.table[:id]
end
但我的解决方案不起作用。有没有更好的方法代替搜掠?若否,有何建议?
==========================================================================
编辑:解决方案
选项A#假设此选项在优惠券表中id=1
选项B#id=2
选择C#id=3
选择D#id=4
选择F#id=5
还可以假设Users表有一个引用Choices表的字段choice_id。
我们修改错误代码如下:
//app/admin/user.rb
filter :choice_id_in, label: 'Filter by the right choice', collection: Coupon.all, as: :select
//app/models/user.rb
ransacker :choice_id,
:formatter => -> (coupon_id) {
if (coupon_id == "5")
ids = User.all.where("choice_id = 3 OR choice_id = 4").map(&:id)
else
ids = User.where("choice_id = ?", coupon_id).map(&:id)
end
(ids.empty?) ? ids << 0: ids #activeadmin translates the queries into IN operator, may get syntax error if empty
# id = 0 is non-existent in Users as id >= 1
ids #maybe is not needed
} do |parent|
parent.table[:id]
end
//app/admin/user.rb
过滤器:选项\u id\u in,标签:“按正确的选项过滤”,集合:优惠券.all,as::select
//app/models/user.rb
洗劫者:选择号,
:格式化程序=>->(优惠券id){
如果(优惠券id=“5”)
id=User.all.where(“choice_id=3或choice_id=4”).map(&:id)
其他的
id=User.where(“choice\u id=?”,优惠券id.map(&:id)
结束
(id.empty?)?id=1
可能不需要ID
}做父母|
父表[:id]
结束
欢迎提出改进建议。感谢@berker的指导。您能详细说明一下“我的解决方案不起作用”吗?你有错误吗?错误的结果?例如,您可以显示它导致的数据库查询以及它们出错的原因。错误的结果。无论我选择什么,都会检索所有行。在进行修改之前,不会发生这种情况。可能我遗漏了一些内容,但无法确定是什么。请查看
日志/development.log
,然后提取记录的sql查询,该查询现在会产生错误的结果。将其粘贴到您的答案中,这样我们就知道SQL是如何出错的。此外,在title==
和else中放置一些调试,以查看在选择F
时该点的值以及if-else的哪一部分。我在if-else-end的两个分支中都出现了一个语法错误,似乎没有涵盖这段代码。另外,我的development.log大约为500米。。不知道如何搜索它。我尝试了fgrep,但输出太大,无法提供帮助。我尝试做但没有提及(因为我认为这没有意义)的是,我使用了这家伙的建议: