【问题标题】:DRYing up Active Record Queries干掉活动记录查询
【发布时间】:2011-03-09 12:57:54
【问题描述】:

我有 2 个相似的查询,我怎样才能把它们弄干?两个查询之间只有 1 个条件不同。

if self.gender_target == "Both"
  return Drop.limit(180).live.where(
  :drops => {:navigation_section_id => 1}  
  ).group(:id).joins(:categories).where(
  :categories => {:id => self.categories}
  ).all
end

if self.gender_target != "Both"
  return Drop.limit(180).live.where(
  :drops => {:navigation_section_id => 1}, 
  :drops => {:gender_target => ["Both", self.gender_target]} #extra condition
  ).group(:id).joins(:categories).where(
  :categories => {:id => self.categories}
  ).all
end

【问题讨论】:

    标签: ruby-on-rails-3 activerecord active-relation


    【解决方案1】:
    @drops = Drop.limit(180).
                  live.
                  where(:drops => {:navigation_section_id => 1}).
                  group(:id).
                  joins(:categories).
                  where(:categories => {:id => self.categories})
    
    if self.gender_target != "Both"
      @drops = @drops.where(:drops => {:gender_target => ["Both", self.gender_target]})
    end
    
    return @drops.all
    

    【讨论】:

      猜你喜欢
      • 2012-08-01
      • 1970-01-01
      • 2016-03-10
      • 2013-02-01
      • 2013-04-23
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多