为用户设置房间

时间:2011-03-02 05:31:38

标签: ruby-on-rails ruby

我正在尝试解决问题,但我找不到解决方案。这是我的代码:

class User < AR::Base
  belongs_to :room
end

class Room < AR::Base
  has_many :users
end

class SetupRooms

  def initialize
    @users = User.all
    @rooms = Room.all
    @room_max_users = @users.size / @rooms.size
  end

  def setup
    groups = @users.in_groups_of(@room_max_users)
    # Now, How Can I fill rooms with users?
  end
end

由于

2 个答案:

答案 0 :(得分:1)

您不需要initialize方法。您的设置可以像这样写

def setup
  Room.all.each_with_index do |room, i|
    room.users = User.find(:all, :limit => room_max_users + i + 1)
    room.save 
  end
end

因此,这会根据用户在数据库中的ID来填充您的房间。只会立即加载所需的用户,因此它不应该对性能至关重要。

btw这个方法应该被定义为一个类方法,也许在Room上,所以你可以像

一样调用它
class Room < AR::Base
  has_many :users

  def self.fill_with_users
    Room.all.each_with_index do |room, i|
      room.users = User.find(:all, :limit => room_max_users + i + 1)
      room.save 
    end
  end    
end


Room.fill_with_users

通过这种方式,您也不需要安装类。

答案 1 :(得分:1)

def setup
  groups = @users.in_groups_of(@room_max_users)
  @rooms.zip(groups).each do |room, group| # now "room" is a Room and "group" is an Array of Users
    group.delete_if { |user| user.nil? } # in_groups_of pads with nil if there are leftover spaces
    room.users = group
  end
end