开发者

Rails MySQL include restrictions

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user    
end

class User < ActiveRecord::Base
  has_many 开发者_JAVA技巧:posts
  has_many :comments
end

I'm trying to pull out Post data, while eager loading the User and Comment data as well, but with the limitation of not loading the Comments which have been blocked (TINYINT field in the Comment table). The following works when there are comments present, but it's causing issues when I load posts that don't have any comments yet:

@post = Post.find(params[:id], 
            :include => {:comments => :user}, 
            :conditions => "comments.blocked = 0")

Any suggestions on how I can run this query such that it will work when no comments are present? Thanks.


What error does it give when you try to do that on a post that has no comments?

Update:

What about this variation?

@post = Post.find(params[:id], 
        :include => {:comments => :user}, 
        :conditions => {:comments => {:blocked => false}})

Conditions on eagerly loaded associations is sort of unusual. Perhaps you should be using the :joins option instead? Or skip eagerly loading the post (since it's just a single one), and have a named scope for the non-blocked comments to use in your view. Something like this perhaps:

@post = Post.find(params[:id])
@comments = @post.comments.where(:blocked => false).all(:include => :user)

(Just typing off the cuff here, not certain that's exactly the right syntax for you)


OK, so after a bit of fiddling, here's the answer (which may seem obvious to some, but the count() function in MySQL was giving me some grief):

@post = Post.find(params[:id], 
            :include => {:comments => :user}, 
            :conditions => "comments.blocked = 0 OR posts.comments_count = 0")

comments_count is a counter_cache field, so I'm getting around the explicit use of the MySQL count() function. It feels like a kludge, but for now I'm OK with that. If anyone has a more elegant solution, please let me know!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜