2016-11-30 39 views
0

我有一個儀表板,允許按不同參數篩選結果。我建立方法來按給定的標準過濾結果。我遇到麻煩的一個領域是如果上一行應該清空活動記錄關係。我應該把一堆如果存在? stat過濾ActiveRecord關係...如果沒有匹配。 (空的活動記錄關係)

def find_website_stats(options = {}) 
    if options[:date_between].present? 
     start_date = options[:date_between].split(/-/).first.to_date 
     end_date = options[:date_between].split(/-/).last.to_date + 1 
    elsif options[:start_date].present? 
     start_date = options[:start_date].to_date 
     end_date = options[:end_date].to_date + 1 if options[:end_date].present? 
    end 

    contractor_name = options[:search_contractor] if options[:search_contractor].present? 
    distributor_name = options[:search_distributor] if options[:search_distributor].present? 
    distributor_ids = options[:with_distributor] if options[:with_distributor].present? 
    contractor_ids = options[:with_contractor] if options[:with_contractor].present? 
    with_country = options[:with_country] if options[:with_country].present? 
    with_state = options[:with_state] if options[:with_state].present? 
    search_city = options[:search_city] if options[:search_city].present? 

    web_stats = self.website_stats 

    if web_stats.present? 
     web_stats = web_stats.where(contractor_id: [*contractor_ids]) if contractor_ids.present? 
     if distributor_ids.present? 
     web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*distributor_ids]).pluck(:website_stat_id) 
     web_stats = web_stats.where(id: [*web_stat_ids]) 
     end 
     web_stats = web_stats.where(date_recorded: start_date..end_date) if start_date.present? && end_date.present? 
     web_stats = web_stats.with_country(with_country) if with_country.present? 
     web_stats = web_stats.with_state(with_state) if with_state.present? 
     web_stats = web_stats.search_city(search_city) if search_city.present? 

     #untested 
     if contractor_name.present? 
     searched_contractor_ids = Brand.search_contractor(contractor_name).pluck(:id) 
     web_stats = web_stats.where(contractor_id: [*searched_contractor_ids]) 
     end 

     if distributor_name.present? 
     searched_distributor_ids = Brand.search_distributor(distributor_name).pluck(:id) 
     web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*searched_distributor_ids]) 
     web_stats = web_stats.where(id: [*web_stat_ids]) 
     end 
     #end untested 
    end 

    web_stats 
end 

我現在明確遇到問題的線路是說web_stat_ids.present?

所以起初我抓住了這個對象所關聯的所有網站統計信息,然後看看是否有給定的分銷商。

如果沒有,則對於給定的經銷商web_stat_ids顯然返回nil

然後,當我去行web_stats.where(編號:[* web_stat_ids]),這顯然會返回我收到了同樣的事情,而不是一個空的活動記錄關係,這是我所需要的嗎?

如果我將它作爲一個空數組,下一個帶有「where」的語句將不起作用,因爲它是一個數組而不是活動的記錄關係。

我知道我可以將這些東西包裝在一堆,如果存在? & &陳述...但我想知道是否有更好的解決方案來解決我的問題?

回答