我在使用 Rails 3 时在预加载时在关联表上使用条件时遇到问题。看起来 Rails 在加载原始模型数据时正在应用条件,因此它不会加载父模型,除非子/关联模型的非零数量匹配条件。这在代码中更容易解释(例如简化):
@post = Post.includes(:comments).where(:comments => { :approved => true }).find(1)
这将生成类似于以下的 SQL 查询:
SELECT DISTINCT `posts`.id FROM `posts`
LEFT OUTER JOIN `comments` ON `comments`.`post_id` = `posts`.`id`
WHERE (`comments`.`approved` = 1) AND (`posts`.`id` = '1')
LIMIT 1
如果没有任何评论满足 approved = 1
条件,则不会返回任何行,因此根本不会加载帖子。
根据评论条件快速加载帖子和相关评论的正确方法是什么?
更新
我仍然很想听到更好的方法,但现在我正在使用以下方法来解决它(适用于深度嵌套的预加载):
@post = Post.find(1)
@comments = @post.comments.where(:approved => true).all
# allows deeper/more complex nesting without getting into SQL:
@post = Post.includes(:author => [ :websites, :photo ]).find(1)
@comments = @post.comments.includes(:editor).where(:approved => true).all
最佳答案
我猜你正在寻找的是 joins
方法,它可以让你把你的条件放在连接定义内,而不是在它之外。例如:
@post = Post.joins("LEFT JOIN comments on posts.id = comments.post_id AND comments.approved = 1").first
不确定条件本身的正确性,但你明白我的意思。
不幸的是,如果您传递数组/哈希,您必须使用那个丑陋的字符串,因为 joins
使用 INNER JOIN。
关于ruby-on-rails - Eager Loaded Association 上的 Rails 3 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892983/