简体   繁体   中英

ActiveAdmin: Filter on method rather than attribute?

I have a method on one of my models like the following:

def current?
  self.parent.start_date <= Time.zone.now.to_date && self.parent.end_date >= Time.zone.now.to_date && !self.archived
end

I'd like to create a simple filter in ActiveAdmin based on the result of this method (a simple select filter called Current with options Yes , No , and Any ) but I can't seem to figure out how.

What's the best approach for filtering on a model method rather than one of its attributes?

The following class method in the ActiveAdmin.rb would return all the records according to the conditions eg ActiveAdmin.current("Yes") or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM