简体   繁体   中英

Rails attr_accessible only for seed.rb?

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM