开发者

validating a has_many relationship that is built

(I apologize for being completely rails illiterate here, I hope I have given enough info)

I am building players that are associated with games, and I am wondering how I get a validation to work for a game when I am building a player. So I have:

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

There is also an association to user (player belongs to both a game and a user) but thats irrelevant for now.

In my players controller I have:

  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
        redir开发者_高级运维ect_to @game
      else
        render 'new'
      end
  end

Which successfully makes a new player and adds it to the game.

But the validation in class Game does not work, presumably because I am not calling create/update/update_attributes for my Game model.

How can I get the validation to run? Should I be remaking def create to use @game.create/update/update_attribute? If so, how?

Thanks for your help.


Not sure what exactly you are trying to accomplish, but here are some thoughts that hopefully lead you down a better path.

  1. You can not validated the maximum number of associated objects with default rails validations. You should be able to write a custom validation.

  2. Your logic using each and push seems very un-rubish and should probably be something like

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜