0
class Campaign < ActiveRecord::Base
  has_many :posts
  has_many :users
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :users
  belongs_to :campaign
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :posts, :join_table => "users_posts"
  belongs_to :campaign
end

如果用户看到这篇文章,我会将他添加到 post.users。我需要找到第一个未观看的用户活动帖子。像这样:

current_user.campaign.posts.where('posts.users not include current_user')
4

1 回答 1

0

Yoshiji 先生,非常感谢!你还记得我include。在我尝试之前join它不适用于 nil 因为INNER JOIN,我用实例方法解决了我的问题:

  def unwatched_post
    campaign.posts.includes(:users).where('users.id != ? OR users.id IS NULL', self.id).first
  end
于 2012-11-08T16:46:33.880 回答