0

I'm teaching myself Rails through PragProg's (apparently outdated - I'm using Rails 3.2.3) Rails for PHP Developers. I've discovered this seeds.rb file that the book doesn't talk about. I've tried to build proper seed entries for a number of things and it's giving me can't mass-assign protected attributes.

After a bunch of searching, it appears my only option is to open these things up by attr_accessible or to turn off the default functionality that blocks mass-assignment. But I want to keep whatever security that setting implies. I don't want these entries to be edited once they've been seeded. I just need to put these into the database first.

What am I not seeing here? How do I seed these data without turning off protection? It seems like seeds should be a special case, allowing mass-assignment where it's otherwise not permitted.

Ben Saufley
  • 3,259
  • 5
  • 27
  • 42
  • I think part of my problem is that I don't entirely understand the utility of said protections. If I can just say `x.name="blah"` and `x.phone="blahblah"` what does stopping me from saying `x=X.new(name => "blah", phone => "blahblah")` do in terms of security? Why should I worry about leaving things that generally won't/shouldn't change protected? – Ben Saufley Jun 22 '12 at 20:19

1 Answers1

1

attr_accessible specifies a list of attributes that should always be open to mass assignment, so if you only want to open these attributes for seeding, then this might not be what you want.

One thing you can do in your seeds file is to use setter methods for each attribute. For example:

admin = User.new do |u|
  u.name = "Foo"
  u.admin = true
end

admin.save!
Bira
  • 373
  • 1
  • 7
  • Alright, fair enough. Does that mean I'm going to have to write out each entry like that, or is there a way to iterate through a hash to build these? – Ben Saufley Jun 22 '12 at 20:48
  • You can indeed iterate through a hash. Something like `hash.each {|k, v| u.send("#{k}=", v) }` should work. – Bira Jun 23 '12 at 01:50
  • Seems to do the trick. I guess I'm still a little confused as to _why_ this works this way. I feel like I'm hacking my own code when my seeds can't be input in the way that the seeds.rb file seems to indicate they should be. – Ben Saufley Jun 25 '12 at 18:03