【发布时间】:2013-12-12 01:16:25
【问题描述】:
如果我有一些类似的模型
class Post < ActiveRecord::Base
has_many :comments
scope :recent ...
喜欢
class Comment
belongs_to :post
scope :written_by_user, ->(user_id) { where(:created_by => user_id) }
...
我想加载所有最近的帖子并懒惰地“包含”用户撰写的任何可用评论。棘手的部分是我不想将帖子限制为用户仅发布带有 cmets 的帖子,我想要所有帖子,即使其中一些没有有效的 cmets。
也许是……
Post.recent.includes(:comments).merge(Comment.written_by_user(current_user))
或
Post.recent.includes(:comments => :written_by_user(current_user))
有没有一种不错的 Railsy 方法可以做到这一点,还是需要 sql 和子查询?
【问题讨论】:
标签: activerecord ruby-on-rails-4