Question

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?

Était-ce utile?

La solution

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)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top