2012-03-20 65 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