Rails has_many includes + where + select 如何组合查询

yeyong14 · December 15, 2014 · Last by zhang_soledad replied at December 17, 2014 · 2125 hits

应用场景:

#user model
has_many :products
#product model
belongs_to :user

def sale
   true
end

现在要查询发布的 VIP 促销的产品

User.includes(:products).where(products: {vip: true})

#product 限制查询
Product.select{|product| product.sale}
#=> 只显示sale为真的值,

如何组合这两种的查询

@lionzixuanyuan 如何组合 model 中的方法查找

includes + where 以后生成的 sql 是 left join 的 而且不符合查询条件的还是会被预载 guide 上推荐使用 joins

You need to Sign in before reply, if you don't have an account, please Sign up first.