Hi All,
I have 3 model, User, Post, Comment with definition like below
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
def self.find_other_user_posts
?
end
end
class User < ActiveRecord::Base
has_many :posts
has_many :comments
has_many :posts_commented_on, :through => :comments, :source => :posts
end
class Comment< ActiveRecord::Base
belongs_to :post
belongs_to :user
end
User can have many post and many comment, question is I want to make method in Post model that returning collection of posts. The method will find posts and comments that doesn't belong to current user. For example there are
Post: A have Comment: A1
Post: B have Comment: B1, B2, B3, B4
Post: C have Comment: C1, C2
Post: D have Comment: nil
Post: E have Comment: nil
Post: F have Comment: F1, F2, F3
current user own Post A, E and Comment A1, B2, so calling :
@posts = Post.find_other_user_posts
will return collection of C, D, F posts.
Thanks
@Terry, following your solution I manage to add
@posts = Post.find( :all,
:include => [:comments],
:conditions => ["posts.user_id <> ? and (comments.user_id <> ? or comments.user_id is null)", current_user, current_user])
And for example data like below Pn for post Cn for comment Un for user and I'm showing the sample data in join form
Post,Post Owner,Comment, Comment Owner
P1,U1,C1,U2
P1,U1,C2,U2
P1,U1,C3,U2
P1,U1,C4,U3 *
P1,U1,C5,U4 *
P1,U1,C6,U5 *
P2,U1
P3,U2
P4,U3,C7,U2
P4,U3,C8,U2
P5,U4
P2, P3, P5 doesn't have a comment and assume current_user is U2, the Post I want to collect is P2 and P5 because U2 is making a comment on P1 and P4 and U2 is the owner of P3 so what left is P2 and P5.
But with above code It return P1, P2, and P5, correct for P2 and P5 but what about P1 ?
Why It's return P1 ? and when I'm drawn it step by step I realize that the row with star (*) is the problem one because these three row is TRUE for the three conditions that I apply in code... and so I'm confuse right now, are there anyway to fix the code with just 1 sql call ?