1

I am making a game, and have a Game model and a User model.

The Game model looks like the following:

class Game < ActiveRecord::Base
  belongs_to :first_user, :class_name => 'User', :foreign_key =>'first_user_id'
  belongs_to :second_user, :class_name => 'User', :foreign_key =>'second_user_id'
  validates_presence_of :first_user, :second_user

  attr_accessible :created_at, :finished_datetime, :first_user_id, :second_user_id, :status, :winner_user_id
  ...

Now, in my controller for the game, I call Game.new. I'm certain that it is being called with current_user and challenge_user, because I checked with logging.

Game.new(:first_user => current_user, :second_user => challenge_user) 

Unfortunately, I get the error:

Can't mass-assign protected attributes: first_user, second_user

I don't understand this since I used attr_accessible, not attr_accessor, so they should be assignable. What should I do differently, Rails?

pdu
  • 10,295
  • 4
  • 58
  • 95
Geoff
  • 9,470
  • 13
  • 52
  • 67
  • 1
    You don't need to specify `:foreign_key` if it can be inferred form `belongs_to`. Just `class_name` has to be enough. – jdoe Jun 20 '12 at 06:04
  • This is wrong: `attr_accessible :first_user, :secound_user` this is right: `attr_accessible :first_user_id, :secound_user_id` because you dont add the accessible to the association you add it for the attribute name! – davidb Jun 20 '12 at 10:38

1 Answers1

1

Everything you pass in on e.g .new or .update_attributes as attributes is "mass-assignment". You need to assign them "manually", like this:

@game = current_user.games.new(params[:my_game_mass_assignment_attributes])
@game.second_user = # your second user

Assigning one attribute at a time is not "mass-assignment" and will work for security reasons (see http://guides.rubyonrails.org/security.html#mass-assignment)

pdu
  • 10,295
  • 4
  • 58
  • 95