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?如果是这样,怎么样?
感谢您的帮助。
多谢了您对1的建议以及2中的ruby建议。我能够成功地将所有代码放入自定义验证中。 – 2011-03-25 00:50:38