I have a users
table and a blocked_users
table. users
has all my authentication data, site preferences, etc, and blocked_users
has a source_id
and a target_id
.
I would like to return a collection of all users that a user has not blocked and that have not blocked the current user.
Right now I have the following code which I execute by calling @user.available_users
but it executes three queries. Is there some way to make this a single query?
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
I added the following method to my User class:
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