【问题标题】:ActiveAdmin: Filter on method rather than attribute?ActiveAdmin:过滤方法而不是属性?
【发布时间】:2013-09-24 19:58:23
【问题描述】:

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

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 的简单选择过滤器,选项为 YesNoAny)但我不能似乎知道怎么做。

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

【问题讨论】:

  • 您能否提供有关conditions 的更多详细信息。第一个想法是使用scope,但需要查看条件以查看是否有效。
  • 另外请指定您要过滤的是记录还是视图或方法调用?
  • @tihom 和 Engineermnky - 请参阅上面的更新。
  • self.archived? 是做什么的?
  • @tihom archived 只是该模型的数据库模式中的一个布尔字段。

标签: ruby-on-rails ruby ruby-on-rails-3 filter activeadmin


【解决方案1】:

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

【讨论】:

  • 抱歉,这个去哪儿了?我的模型的 ActiveAdmin.register 块? “过滤器”方法会是什么样子?感谢您的帮助。
  • 这在ActiveAdmin.rb 文件中。它允许您通过调用ActiveAdmin.current 来访问过滤后的记录。 ActiveAdmin 是您应用中的模型吗?
  • 不,ActiveAdmin 是我在项目中使用的 gem (github.com/gregbell/active_admin)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2016-06-22
相关资源
最近更新 更多