2012-06-28 44 views
0

一个排除我有一个users表和blocked_users表。 users有我所有的认证数据,现场的喜好等,并blocked_userssource_idtarget_id续集进行以下一个查询运行从连接表

我想回到所有用户,用户没有堵塞,并且没有阻止当前用户的集合。

现在我有下面的代码,我通过调用@user.available_users执行,但它执行三个查询。有没有办法让这个单一的查询?

class User < Sequel::Model 

    one_to_many :blocked_users,  :key=>:source_id 
    one_to_many :blocked_by_users, :key=>:target_id, :class => BlockedUser 

    def block_user(id) 
    BlockedUser.create({source_id:self.id, target_id:id}) 
    end 

    def blocked_user_ids 
    self.blocked_users.map{|bu| bu[:target_id]} 
    end 

    def blocked_by_user_ids 
    self.blocked_by_users.map{|bu| bu[:target_id]} 
    end 

    def available_users 
    User.exclude(:id=>self.blocked_users.map{|bu| bu[:target_id]}).exclude(:id=>self.blocked_by_users.map{|bu| bu[:target_id]}) 
    end 
end 

我添加下面的方法来我的用户等级:

def test_avail 
    User.exclude(:blocked_users=>self).exclude(:blocked_by_users=>self) 
    end 

1.9.3p0 :001 > User.all.first.test_avail 
    INFO - (0.000732s) SELECT * FROM `users` 
Sequel::Error: invalid association class User for association :blocked_users used in dataset filter for model User, expected class BlockedUser 

回答

2

通过协会的大力支持使用过滤器可能是最简单的:

def available_users 
    User.exclude(:blocked_users=>self).exclude(:blocked_by_users=>self) 
end 
+0

嘿,所以我说的变化在上面的问题,但现在与片断我得到 续集::错误:无效的关联类用户的关联:在数据集过滤器用于模型用户blocked_users,预计类BLOCKEDUSER – jdkealy

+0

我的错。如果blocked_users和blocked_by_users是自引用的many_to_many关联,则该代码将工作。相反,您正在使用单独的BlockedUser类和one_to_many关联。我不确定你为什么这样设置它。根据您目前的代码,你应该能够做到User.exclude(:ID => self.blocked_users_dataset.select(:target_id))。 –

相关问题