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

hexawing · April 05, 2017 · Last by theblock24block replied at April 13, 2017 · 1434 hits

比如我在 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
Reply to geekerzp

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

Reply to hexawing

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

Reply to ecnelises

你这个不对

Reply to hexawing

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

1.day.ago.to_date
6 Floor has deleted

简单点就这样

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
You need to Sign in before reply, if you don't have an account, please Sign up first.