这是我的模型结构:
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
当我查询数据库(使用活动记录)时,我应该能够执行以下操作:
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
上面返回了一个组的记录和我最初查询的用户 ID。但是由于某种原因,当我在 Group 内部运行这个方法时,我得到了一个错误的返回:
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