干掉活动记录查询

时间:2011-03-09 12:57:54

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

我有两个相似的查询,我怎么能干它们?两个查询之间只有一个条件不同。

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

1 个答案:

答案 0 :(得分:0)

@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