2012-03-20 93 views
2

有没有一种方法来执行.includes和指定外部左连接。外左加入包括导轨3

原:

@post = Post.includes(:comments).where("comments.spam = ?", false).where(:id => params[:id]).first 
@comments = post.comments 

的愿望是模仿:

@post = Post.find(params[:id]) 
@comments = post.comments.where(:spam => false) 

除了使用包括将在一个预先加载的方式执行它(如果说我有多个帖子)。

感谢您的帮助。 贾斯汀

+0

我做了这样的事情,这是我如何实现它: [堆栈溢出] [1] [1]:http://stackoverflow.com/questions/15441012/any-possible-way-to-add-parameters-to-on-clause-on-include-left-joins-on-rails/16551544#16551544 – 2013-05-14 19:45:50

回答

0

我会做到以下几点:

class Post < ActiveRecord::Base 
    has_many :comments 

    has_many :non_spam_comments, :through => :comments, :conditions => {:spam => false} 
    has_many :spam_comments, :through => :comments, :conditions => {:spam => true} 
end 

然后,你就可以做到:

@posts = Post.where(:user_id => current_user.id).includes(:non_spam_comments) 
@posts.each do |post| 
    post.non_spam_comments.each do |comment| 
    // Some comment operation 
    end 
end