Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bypass attr_accessible in seeds.rb

I cannot really find a clean way to bypass attr_accessible when creating seed data. I would like to be able to use mass assignment without any problems, since i know that this seed file is totally safe.

Is there a clean way to force Rails 3 to accept those ?

like image 928
Spyros Avatar asked May 19 '12 23:05

Spyros


2 Answers

Here's a quick hack (thanks Mike), put this at the top of your seeds.rb:

# Dodge the mass assignment
User.send(:attr_accessible, :username)
User.send(:attr_accessible, :admin)

Now you can call this with ease without cluttering up your model (using :as => :seed):

@user = User.find_or_create_by_username(:username => 'ryanonrails', :admin => true)
like image 77
ryanjones Avatar answered Sep 30 '22 00:09

ryanjones


#in model
attr_accessible :name, :role,.... :as => :seed

#in seed.rb
model.assign_attributes({name: "Putin", role: "president"....},:as => :seed)
model.save
like image 26
Yuri Barbashov Avatar answered Sep 29 '22 23:09

Yuri Barbashov