新手问题 请教一个 scope, select in 写法

luffycn · January 23, 2015 · Last by suffering replied at January 28, 2015 · 1822 hits

hello, 各位

stores 表里面有两个字段 user_id 关联 user 表,current_user.stores name

在 product model 里的 scope,想要做到 select * from products where store_name in ('a1', 'a2', 'a3')

其中 'a1', 'a2', 'a3' ,是从 current_user.stores 获取 这个 scope 要怎么写了

scope :your_scope, -> {|store_names| where(store_name: store_names)}
Product.your_scope current_user.store_ids

@henlonj , 思路没有问题

Product.joins(:stores).where(stores: { user_id: current_user.id })

支持@kungs的写法,这种需求不推荐使用 scope.

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