这是我的模型结构:
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
在我的用户模型中,我有一个名为subscriptions的方法:
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 I中运行此方法时,返回false:
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
答案 0 :(得分:1)
group_admins
返回GroupAdmin对象的集合。这些可能(通过他们的user_id)对应用户,但他们实际上不是用户,因此group_admins.include?(user)
只能返回false。
根据您的工作情况,您可以在include?
上致电group_admins.collect {|ga| ga.user}
或搜索具有相应user_id
值的GroupAdmin。