2016-02-17 244 views
2

我正在使用ActiveAdmin,我试图实现我自己的过滤器。自定义ActiveAdmin过滤器

  1. 过滤器按天/周/月的价格(虚拟属性)
  2. 过滤器,大于和小于

businesses.rb

filter :period_eq, as: :select, collection: [['day', 'day'], ['week', 'week']] 
filter :price_lteq, as: :string 
filter :price_gteq, as: :string 

业务。 rb

ransacker :period, 
    formatter: -> period { 
    from = { 
     day: Time.now.beginning_of_day, 
     week: 1.week.ago.beginning_of_day, 
     month: 1.month.ago.beginning_of_day, 
     year: 1.year.ago.beginning_of_day, 
    }[period.to_sym] 
    Business.where('updated_at >= ?', from).pluck(:id) 
    }, splat_params: true do |parent| 
    parent.table[:id] 
end 
ransacker :price do |parent| 
    # equivalent to Business.where('(owner_price + comission) >= ?', price) 
end 

我需要2个单独的字段价格,而不是ActiveAdmin默认[lt,gt,eq]下拉列表。

我想不通,哪个Arel表情我应该放在歹徒身上?
什么是我的问题的替代解决方案?我的意思是避免使用ransack。

UPDATE
我设法得到:价格过滤工作:

filter :price, as: :numeric_range 

ransacker :price, 
    formatter: -> price { 
    price.to_s.gsub /[\u00A0\s]+/, '' 
    }, splat_params: true do |parent| 
    Arel::Nodes::InfixOperation.new('+', 
     parent.table[:comission], parent.table[:owner_price]) 
end 

但还是需要帮助:段过滤

+1

你有没有试过为'price_lteq'和'price_gteq'指定'as'选项?我认为它在模型上查找是否存在列/属性,或者忽略它们。 – codenamev

+0

@codenamev谢谢,这工作。后续问题,我可以创建具有1个标签和2个输入字段(from,to)的过滤器吗?我的代码创建2个标签的过滤器。 – leemour

回答

0

移动我的答案;-)

评论当过滤器不符合模型上的列或属性时,必须指定过滤器的as选项:

filter :price_lteq, as: :string 

如果您正在寻找一个范围,ActiveAdmin有numeric_range。尝试这样的:

filter :period, as: :select, collection: [['day', 'day'], ['week', 'week']] 
filter :price, as: :numeric_range 

ransacker :period, (period_name) -> { 
    { 
    day: Time.now.beginning_of_day, 
    week: 1.week.ago.beginning_of_day, 
    month: 1.month.ago.beginning_of_day, 
    year: 1.year.ago.beginning_of_day, 
    }[period.to_sym] 
} do |parent| 
    parent.table[:updated_at] 
end 

ransacker :price do |parent| 
    formatter: -> price { 
    price.to_s.gsub /[\u00A0\s]+/, '' 
    }, splat_params: true do |parent| 
    Arel::Nodes::InfixOperation.new('+', parent.table[:comission], parent.table[:owner_price]) 
end 
+0

谢谢。图numeric_range out。我没有默认它(可能是旧的AA版本),所以通过创建新的输入类型添加。仍然问题是我在抄袭者内部写什么? – leemour

+0

我为您的解决方案获得了'(owner_price + comission)'未定义的方法'lteq'。和掠夺:在我的问题代码期间不起作用。 – leemour

+0

我设法得到:价格使用'Arel :: Nodes :: InfixOperation.new('+', parent.table [:连锁],parent.table [:owner_price])''。更新的问题。你可以帮我:周期过滤器? – leemour