在Rails中查找数据

gkr*_*dvl 0 ruby-on-rails

我有3个模型,用户,发布,评论和定义如下

    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
Run Code Online (Sandbox Code Playgroud)

用户可以有很多帖子和很多评论,问题是我想在Post模型中制作返回帖子集合的方法.该方法将查找不属于当前用户的帖子和评论.例如,有

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
Run Code Online (Sandbox Code Playgroud)

当前用户自己的帖子A,E和评论A1,B2,所以呼叫:

@posts = Post.find_other_user_posts
Run Code Online (Sandbox Code Playgroud)

将返回C,D,F帖子的集合.

谢谢

@Terry,按照我设法添加的解决方案

@posts = Post.find( :all,
    :include => [:comments],
    :conditions => ["posts.user_id <> ? and (comments.user_id <> ? or comments.user_id is null)", current_user, current_user])
Run Code Online (Sandbox Code Playgroud)

例如,下面的Pn数据用于发布Cn用于评论Un用户,我在连接表单中显示示例数据

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
Run Code Online (Sandbox Code Playgroud)

P2,P3,P5没有评论并且假设current_user是U2,我想要收集的帖子是P2和P5,因为U2正在对P1和P4发表评论而U2是P3的所有者所以剩下的就是P2和P5.

但是使用上面的代码它会返回P1,P2和P5,对P2和P5进行校正,但是P1呢?

为什么它会回归P1?当我逐步绘制它时,我意识到带有星号(*)的行是问题之一,因为对于我在代码中应用的三个条件,这三行为TRUE ...所以我现在很困惑,无论如何只用1 sql调用修复代码?

Ter*_*ber 5

@posts = Post.find(:all,
           :include => [:comments],
           :conditions => ["posts.user_id <> ? and comments.user_id <> ?",
                           user.id,
                           user.id])
Run Code Online (Sandbox Code Playgroud)

请注意,此处的"user"不是Post模型的关联用户.查看使用named_scopes来实现此行为.