开发者

Set rooms for users

开发者 https://www.devze.com 2023-02-14 11:34 出处:网络
I\'m trying to resolve a problem but I don\'t find the solution. This is my code: class User < AR::Base

I'm trying to resolve a problem but I don't find the solution. This is my code:

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 ro开发者_开发问答oms with users?
  end
end

Thanks


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


You do not need the initialize method. Your setup can be written like this

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

So this fills your rooms with users, based on their id in the database. Only the needed users are loaded at once so it should not be performance critical.

btw this method should be defined as a class method, perhaps on Room so you could invoke it like

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

In this way you won't need your setup class as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消