【发布时间】:2015-04-29 00:40:06
【问题描述】:
我有一个users 表和一个blocked_users 表。 users 拥有我所有的身份验证数据、网站偏好等,blocked_users 拥有 source_id 和 target_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
我在我的 User 类中添加了以下方法:
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
【问题讨论】: