我在我的一个模型上有一个方法,如下所示:
def current?
self.parent.start_date <= Time.zone.now.to_date && self.parent.end_date >= Time.zone.now.to_date && !self.archived
end
我想基于此方法的结果在ActiveAdmin中创建一个简单的过滤器(一个名为Current
的简单选择过滤器,其中包含选项Yes
,No
和{{1但是我似乎无法弄清楚如何。
过滤模型方法而不是其中一个属性的最佳方法是什么?
答案 0 :(得分:0)
ActiveAdmin.rb
中的以下类方法将根据条件返回所有记录,例如ActiveAdmin.current("Yes")
或ActiveAdmin.current("No")
。
def self.current(inp = "Yes") # default inp is "Yes"
d = Time.zone.now.to_date
return case inp
# when inp == "Yes" it would return all the records with archived == false (won't return archived == nil)
# AND parents with start_date <= d and end_date >= d
when "Yes"
where(archived: false ).
joins(:parent).
where("parents.start_date <= ? AND parents.end_date >= ?",d,d)
# when inp == "No" it would return all the records with archived == true (won't return archived == nil)
# AND parents with start_date > d OR end_date < d
when "No"
where(archived: true ).
joins(:parent).
where("parents.start_date > ? OR parents.end_date < ?",d,d)
# when inp = "Any" return all records
when "Any"
scoped
# return all records if inp does not match any of the above options
else
scoped
end
end