Finding data in Rails

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
    class User < ActiveRecord::Base
      has_many :posts
      has_many :comments
      has_many :posts_commented_on, :through => :comments, :source
=> :posts
    class Comment< ActiveRecord::Base
      belongs_to :post
      belongs_to :user

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.


If you want that to be a class method on Post you'll have to pass in
the id of the user I think.

How about something like:

  def self.find_other_users_posts(this_user)
    self.find(:all, :conditions => ["user_id <> ?",])



My two cents would be to have a look at Searchlogic, It's my latest
favorite and I find a use for it in every rails project I do...

Make it a named_scope instead of a function so that it can be chained
in the future.

Class Post
named_scope :other_users_posts, lambda { |user_object| {:conditions=>
["user_id <> ?",]}}

You can then do a Post.other_users_post(User.first) as an example and
chain it just like other active record finder functions.

Ah, @Roy, sorry but the solution doesn't work.
The question is to return C, D, F because current user doesn't own C,
D, F, and current user doesn't make any comment on C, D, F.
Actually there are 2 condition I want to achieve, I want to return
collection of post that :
1. Other than my own post OR Haven't read it yet OR Post not created
by me.
2. And Post that haven't got my Comment at all because if I'm already
make a Comment on a Post then it assume that I'm already read the post

So what I want is a Post that is very very new to me and I want to
read it and make Comment. How to do that ?

@Roy, wow I search and learn "searchlogic" and it's very very logic
and super duper easy, thanks.
@Mukund, hanks for named_scope suggestion I search the article and
learn it and found out IT'S VERY COOL, especially the chain part. :slight_smile:

@heimdull, wow I search and learn "searchlogic" and it's very very
and super duper easy, thanks. (sorry, mistype)