2

Is there a way to perform .includes and specify an outer left join.

Originally:

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

The desire is to mimic:

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

Except using includes would perform it in an eager loading fashion (if say I had multiple posts).

Thanks for the help in advanced. Justin

Justin
  • 631
  • 2
  • 7
  • 13
  • I did something like this, here is how i achieved it: [Stack Overflow][1] [1]: http://stackoverflow.com/questions/15441012/any-possible-way-to-add-parameters-to-on-clause-on-include-left-joins-on-rails/16551544#16551544 – Bernardo Mendes May 14 '13 at 19:45

1 Answers1

0

I would do the following:

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

Then, you'll be able to do:

@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
Carlos Drew
  • 1,633
  • 9
  • 17