查询多对多关系

时间:2015-08-06 22:17:15

标签: sql ruby-on-rails

我正在尝试创建两种类型用户的数组:优先级和成员。 Priorty用户创建了事件,而成员是那些没有创建事件的人。下面的函数应该将用户排序为优先级或成员,首先分配优先级用户,如果事件中有空间(如客人所示),它将随机添加成员用户。我收到了以下错误消息:

undefined method `id' for #<User::ActiveRecord_AssociationRelation:0x00000001c27828> 

如何获取User类,而不是ActiveRecord_AssociationRelation类?

event.rb

class Event < ActiveRecord::Base
    has_many :event_users
    has_many :users, :through => :event_users
    belongs_to :creator, :class_name => "User", :foreign_key => "user_id"
end

eventuser.rb

class EventUser < ActiveRecord::Base
 belongs_to :user
 belongs_to :event
end

user.rb

class User < ActiveRecord::Base
  has_many :event_users
  has_many :events, :through => :event_users
  has_many :created_events, :class_name => "Event"

  def do_randomize
    priority = self.users.where('events_created > ?', 0)
    regular = self.users.where('events_created = ?', 0)
    winners = []
    priority_winners = priority.limit(guests).order('users.events_created    DESC')
    remaining_slots = self.guests - priority_winners.count

    if remaining_slots <= 0
        winners << priority_winners
    else
        regular_winners = regular.limit(remaining_slots).order("RANDOM()")
        winners << priority_winners << regular_winners
    end
    winners.each do |winner|
        puts winner.id
    end
end

1 个答案:

答案 0 :(得分:2)

你比你想象的更接近。这一行是你的问题:

winners << priority_winners

数组上的<<(通常称为“append”)运算符实际上将右侧参数作为 new,single element 添加到数组中。含义,[] << 1返回[1]。但是你正在做的更像[] << [1],它将右手数组作为新元素添加到原始数组并返回[[1]]。因此,迭代它会返回您的关联,而不是每个获胜者。

要解决此问题,只需使用数组concatenation operator代替+

winners += priority_winners

<<的其他用途也一样:

winners += priority_winners + regular_winners