当使用嵌套包含或联接时,在where子句中使用OR

时间:2016-10-19 14:16:19

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

在处理带有关联的嵌套包含时,我必须在where子句中使用OR。 我有一个ActiveRecord查询,如下所示:

  Inventory.includes(:category,:inventory_tiers,:modifiers=>[:modifier_measures,:modifier_tiers])
  .where(
    :categories => { category_tag: 'Dry'},
    :location_id =>12,
    :inventory_tiers => {:tier => 1}),
    modifiers: {category_tag:"Wet"},
    modifier_tiers: {tier:1}
)

其中where子句对所有条件使用AND。 但是我想在最后两个条件中使用OR,例如:

Inventory.includes(:category,:inventory_tiers,:modifiers=>[:modifier_measures,:modifier_tiers]).where("categories.category_tag=? AND location_id=? AND inventory_tiers.tier = ? OR modifiers.category_tag=? OR modifier_tiers.tier=?", "Wet",12,1,"Wet",1).select("inventories.id,inventories.name,inventories.photo,inventory_tiers.sell_price, modifiers.id,modifiers.name,modifiers.price,modifier_measures.id as measure_id,modifier_measures.name as measure,modifier_measures.price as measure_price,modifier_measures.measure_value")

但它不起作用。 我怎么能重写语法?

1 个答案:

答案 0 :(得分:0)

As commented, without knowing the actual version of Rails you're using, I'll presume it's Rails 3... In which case, I'd suggest using Arel. Something like:

Inventory.includes(:category, :inventory_tiers, modifiers: [:modifier_measures, :modifier_tiers])
  .where(categories: { category_tag: 'Dry' }, location_id: 12, inventory_tiers: { tier: 1 })
  .where(Modifier.arel_table[:category_tag].eq("Wet").or(ModifierTier.arel_table[:tier].eq(1)))

I haven't tested this, but the above should get you on the right path.