Rails 请教,如何在一个 model 中使用其它 model 里的查询条件……

hexawing · 2017年04月05日 · 最后由 theblock24block 回复于 2017年04月13日 · 1433 次阅读

比如我在 Post 模型里写了一个叫 recent 的查询

def self.recent
    where('created_at >= ?', Date.today - 1)
end

然后比如有个需求是:列出所有最近发过帖子的用户,我可以这么写:

def self.active
    where('posts.created_at >= ?', Date.today - 1).joins(:posts) # 关联假设已经写了
end

这个 where 和上面那段是一样的,我能“借过来”用吗?

class Post
  scope :recent, -> { where('created_at >= ?', Date.today - 1) }
end

def self.active
  where('posts.created_at >= ?', Date.today - 1).joins(:posts).merge(Post.recent)
end
geekerzp 回复

我的意思是: where('posts.created_at >= ?', Date.today - 1)这个逻辑写了两遍,能偷点懒吗……

hexawing 回复

把这个 where 子句写成 scope include 一下 Concern 这个模块 然后写一个模块 在 included 的 block 里面定义这个 scope (好像更麻烦了)

ecnelises 回复

你这个不对

hexawing 回复

这两个逻辑看起来像,实际上完全不相关还是不要耦合在一起比较好

1.day.ago.to_date
6 楼 已删除

简单点就这样

def self.active
  where("id in (?)", Post.recent.pluck(:user_id).uniq)
end

复杂的可以这样吧

def self.active
  records = Post.recent.select(:user_id).uniq.to_sql
  joins("join (#{records}) as result on users.id = result.user_id")
end
def self.active
  where 'id in (?)', Post.recent.distinct.pluck(:user_id)
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号