1

我在我的一个模型上有一个方法,如下所示:

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,用 options YesNo和调用Any),但我似乎不知道怎么做。

过滤模型方法而不是其属性之一的最佳方法是什么?

4

1 回答 1

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
于 2013-09-25T19:14:51.917 回答