2016-02-17 245 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