Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails error: Can't mass-assign protected attributes

I am trying to build an extremely simple AddressBook rails application. However, I am getting this error "Can't mass-assign protected attributes: city_id". How can I fix this? Please feel free to add any comment/suggestion to your answer regarding the rails code below. Thanks.

How I created the project (from scratch):

rails new demo rails generate model City name:string rails generate scaffold User name:string city:references rake db:migrate 

db/seeds.db:

City.create(name: "City1") City.create(name: "City2") City.create(name: "City3") 

rake db:seed

changed this line <%= f.text_field :city %> from app/views/users/_form.html.erb to <%= f.collection_select :city_id, City.all, :id, :name %>

changed user.rb auto-generated line belongs_to :city to has_one :city.

added belongs_to :city to city.rb

P.S: I am using Rails 3.2.3 and Ruby 1.9.3.

like image 942
nunos Avatar asked Apr 07 '12 00:04

nunos


1 Answers

There was an important security change rails 3.2.3 that requires you to allow mass assignment explicitly by setting config.active_record.whitelist_attributes to false

https://weblog.rubyonrails.org/2012/3/30/ann-rails-3-2-3-has-been-released/

http://www.h-online.com/security/news/item/Rails-3-2-3-makes-mass-assignment-change-1498547.html

alternatively (and better), instead of allowing mass assignment, you just have to set the attr_accessible for the attributes in your model that you want to be able to change, e.g.

attr_accessible :city_id, :name # list all fields that you want to be accessible here 

Please check the rails security guide for more information about mass-assignment in rails.

like image 102
tmaximini Avatar answered Oct 01 '22 02:10

tmaximini