通过关联找到所有没有关联的

时间:2012-11-08 15:51:27

标签: mysql ruby-on-rails join associations

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。我需要找到第一个未见过的用户广告系列帖子。像这样的Smth:

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

1 个答案:

答案 0 :(得分:0)

MrYoshiji,非常感谢!你记得我include。在我尝试join并且因为INNER JOIN而无法使用nil之前,我使用实例方法解决了我的问题:

  def unwatched_post
    campaign.posts.includes(:users).where('users.id != ? OR users.id IS NULL', self.id).first
  end