我有一个仪表板,允许通过不同的参数过滤结果。我构建了按给定标准过滤结果的方法。我遇到问题的一个方面是前一行是否应该使活动记录关系无效。我应该把一堆如果存在吗? STAT
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(id:[* web_stat_ids])时,显然会返回我以前的相同的东西,而不是一个空的活动记录关系,这就是我需要它?
如果我将它设为空数组,那么带有“where”的下几个语句将不起作用,因为它是一个数组而不是一个活动的记录关系。
我知道我可以将这些东西包装成一堆如果存在的话? &安培;&安培;陈述......但我想知道我的问题是否有更好的解决方案?
答案 0 :(得分:0)
如果有其他人正在寻找此项,请从此SO帖子中找到答案:How to return an empty ActiveRecord relation?
Model.none rails 4 +