English 中文(简体)
铁路3:主动记录结果和阵列#包括?
原标题:Rails 3: ActiveRecord results and Array#include?

以下是我的模型结构:

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
最佳回答

group_admins 返回组Admin 对象的集合。 它们可能( 通过其用户_ id) 与用户相对应, 但实际上不是用户, 所以 group_admins. 包括? (user) 只能返回错误 。

取决于您在做些什么,您可以调用 包括? on group_admins.call {ga_ga_ga_ga.user__/code> 或搜索具有相应 user_id 值的群集Admin。

问题回答

暂无回答




相关问题
Codeigniter WHERE on "AS" field

I have a query where I need to modify the selected data and I want to limit my results of that data. For instance: SELECT table_id, radians( 25 ) AS rad FROM test_table WHERE rad < 5 ORDER BY rad ...

Problem find joined table in rails

I have model represent association rule (Body => Head) def Item has_many :heads has_many :bodies ... end def Rule has_many :heads has_many :bodies ... end def Body belongs_to :item belongs_to :rule ...

FreeTDS Bad token from the server (SQL Server)

Today we had a lot more activity than normal between our Ruby on Rails application and our remote legacy SQL Server 2005 database, and we started getting the error below intermittently. What is is? ...

Castle ActiveRecord: one-to-one

While playing around with one-to-one associations in castle activerecord I stumbled upon the following problem: I m trying to model a one-to-one relationship (user-userprofile in this case). I ...

Sending email updates: model or observer?

I have an Event model, which stores an event feed for each user. I also need to email the updates to users which have enabled email notifications in their profile. From an architectural point of view,...

activerecord has_many :through find with one sql call

I have a these 3 models: class User < ActiveRecord::Base has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions end class Permission < ActiveRecord::...