以下是我的模型结构:
A User has and belongs to many groups
A Group has many subscriptions
A Group has and belongs to many users
A Group has many GroupAdmins
A Subscription belongs to a group
A GroupAdmin belongs to a user
A GroupAdmin belongs to a Group
当我查询 DB (使用主动记录) 时, 我应该能够做这样的事情:
u = User.find 47238
在我用户模型中,我有一个方法叫做订阅:
def subscriptions
self.groups.where(:status => active ).collect { |group| group.subscriptions.where("subscriptions.status = ? AND subscriptions.expiration_date > ?", active , "#{Time.zone.now}").last }.flatten
end
然后继续我的查询:
u.subscriptions.first.group.group_admins
上面给我一个组的记录, 用户代号我无时无刻不在查询。 但出于某种原因, 当我在组内运行这个方法时,
def is_group_admin?(user)
self.group_admins.include? user
end
工作守则:
def is_admin?(user)
self.group_admins.collect { |ga| ga.user }.include? user
end