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

yeyong14 · 2014年12月15日 · 最后由 zhang_soledad 回复于 2014年12月17日 · 2123 次阅读

应用场景:

#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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号