简体   繁体   English

Rails attr_access仅适用于seed.rb?

[英]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 . 我正在通过PragProg(显然已经过时-我正在使用Rails 3.2.3) 为PHP开发人员教Rails。 I've discovered this seeds.rb file that the book doesn't talk about. 我发现了本书没有提到的seed.rb文件。 I've tried to build proper seed entries for a number of things and it's giving me can't mass-assign protected attributes . 我已经尝试为许多事情构建适当的种子条目,这使我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. 经过一堆搜索之后,看来我唯一的选择是通过attr_accessible打开这些内容,或者关闭阻止批量分配的默认功能。 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. attr_accessible指定应始终对批量分配开放的属性列表,因此,如果您只想打开这些属性进行播种,则可能不是您想要的。

One thing you can do in your seeds file is to use setter methods for each attribute. 您可以在种子文件中做的一件事是对每个属性使用setter方法。 For example: 例如:

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

admin.save!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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