Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to seed a Rails 3.1 app with scoped mass assignment

How does Rails 3.1 (RC4) and scoped mass assignment expect us to work with seeds.rb when loading a list of data.

For example. I normally have something like:

City.create([
  { :name => 'Chicago' }, 
  { :name => 'Copenhagen' }, 
  ...
]) 

Which creates over 100+ cities. this doesn't work anymore since the City model has a scoped mass assignment :as => :admin.

As far as I know, the .create() method does not allow us to throw in :as => :admin. Only .new() and .update_attributes() allows us to do this with :as => :admin.

So doing something like (below) is cumbersome (especially for 100+ records):

city1 = City.new({ :name => 'Chicago' }, :as => :admin)
city1.save
city2 = City.new({ :name => 'Copenhagen' }, :as => :admin)
city2.save

Any thoughts on this?

like image 393
Christian Fazzini Avatar asked Dec 17 '22 12:12

Christian Fazzini


1 Answers

You can do the following:

City.create([
  { :name => 'Chicago' }, 
  { :name => 'Copenhagen' }, 
  ...
], :without_protection => true) 

This completely overrides the mass assignment protection - so be sure to only use this in say the seeds.

like image 100
Joerg Avatar answered Feb 22 '23 23:02

Joerg