0

这是我的模型结构:

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
4

1 回答 1

1

group_admins返回 GroupAdmin 对象的集合。这些可能(通过它们的 user_id)对应于用户,但它们实际上不是用户,因此group_admins.include?(user)只能返回 false。

根据您的操作,您可以调用include?group_admins.collect {|ga| ga.user}搜索具有适当user_id值的 GroupAdmin。

于 2012-05-24T22:51:35.850 回答