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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With