Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't mass-assign protected attributes attr_accessor and attr_accessible

in rails 2.3.11, I have below in model

attr_accessor :person_id

and in controller

@project.person_id = current_user.id

now, I am converting this in rails 3.2.11 and I am getting

Can't mass-assign protected attributes: person_id

so I changed in model, I removed :person_id from attr_accessor and add below line

attr_accessible :person_id

but I am uisng person_id in controller, here it is

@project.person_id = current_user.id

I am getting this now

NoMethodError in ProjectsController#create

undefined method `person_id=' for #<Project:0x19cc51a>

any idea or help, How can I fix this? How can I handle both attr_accessor & attr_accessible?

like image 578
AMIC MING Avatar asked May 07 '13 22:05

AMIC MING


1 Answers

attr_accessor :person_id and attr_accessible :person_id are not the same.

attr_accessor is the Ruby method. In short its shortcut for methods:

def person_id
  @person_id
end

def person_id=(value)
  @person_id = value
end

attr_accessible is the Rails method. Which gets list of attributes allowed to be mass-assigned. You can read about here.

Thus in your case you need both of them.

attr_accessor :person_id
attr_accessible :person_id
like image 198
ck3g Avatar answered Nov 15 '22 13:11

ck3g