2011-03-23 80 views
2

(我为是道歉完全轨文盲在这里,我希望我已经给了足够的信息)确认这是建立一个的has_many关系

我建立了与games相关players,我想知道我是怎么得到当我正在建立一个球员的时候验证为一个游戏工作。所以,我有:

class Game < ActiveRecord::Base 
    has_many :players, :dependent => :destroy 

    #does not work or is ineffective due to how I made my player's create in the controller 
    validates :players, :length => { :maximum => 6 } 
end 


class Player < ActiveRecord::Base 
    belongs_to :game 
end 

还有一个关联的用户(玩家同时属于游戏和用户),但现在那无关紧要。

在我的球员控制器我有:

def create 
    @game = Game.find(params[:game_id]) 

    @players_in_game = Array.new 
    @game.terra_players.each do |i| 
     @players_in_game.push(i.user_id) 
    end 

     @player = current_user.terra_players.build(:terra_game => @terra_game) 
     if @player.save 
     redirect_to @game 
     else 
     render 'new' 
     end 
    end 

,成功地使一个新的播放器,并将其添加到游戏中。

class Game验证不起作用,大概是因为我没有为我的Game模型调用create/update/update_attributes。

我怎样才能让验证运行?我应该重新编制def create以使用@ game.create/update/update_attribute?如果是这样,怎么样?

感谢您的帮助。

回答

2

不知道你到底想要完成什么,但是这里有一些想法可以让你走上更好的道路。

  1. 您无法使用默认导轨验证验证关联对象的最大数量。您应该可以编写自定义验证。

  2. 使用每把你的逻辑似乎非常不rubish,应该大概是这样的

    @players_in_game = @ game.terra_players.map(&:USER_ID)

+0

多谢了您对1的建议以及2中的ruby建议。我能够成功地将所有代码放入自定义验证中。 – 2011-03-25 00:50:38

相关问题