Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shoulda matchers should validate_uniqueness_of failing with scope

I have 3 models, user, game, and player. There's basically a many to many relationship between users and games, with players as the join table, except players have other info so it has its own model.

A player needs a unique combo of game id and user id, so I tried to say in player:

validates_uniqueness_of :user_id, :scope => :game_id

and then in my spec, I said (using shoulda matchers):

it { should validate_uniqueness_of(:user_id).scoped_to(:game_id)}

here are the relationships the player defines:

belongs_to :game, :inverse_of => :players
belongs_to :user, :inverse_of => :players

yet I'm getting an ActiveRecord::statementinvalid error on that spec

ActiveRecord::StatementInvalid: Mysql2::Error: Column 'game_id' cannot be null: INSERT INTO `players` ETC...

Any idea what's going wrong?

like image 643
bdwain Avatar asked Apr 28 '13 21:04

bdwain


1 Answers

It is a known issue. It gives this error if the scoped field is dependent on the model and is also set to :null => false.

Also, do have a look at rails Column cannot be null:

like image 193
kiddorails Avatar answered Sep 22 '22 05:09

kiddorails