更新:我在Ruby 1.8上运行。存储库的链接 github.com/lauherk/sample_app
我正在学习Micheal hartl的Ruby on Rails教程,在第9章中,我遇到了使用示例用户填充数据库的问题 http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users?version=3.2#sec:sample_users
我的耙子的代码是:
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
User.create!(:name => "Example User",
:email => "example@railstutorial.org",
:password => "foobar",
:password_confirmation => "foobar")
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(:name => name,
:email => email,
:password => password,
:password_confirmation => password)
end
end
end
运行两者后:
bundle exec rake db:reset
bundle exec rake db:populate
我从命令行收到以下错误:
rake aborted!
Can't mass-assign protected attributes: Lawrence Kertzmann
/Library/Ruby/Gems/1.8/gems/activemodel-3.2.2/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
(每次运行耙子时都会更改特定名称)
我已经检查并确保在我的用户模型中我有代码
attr_accessible :name, :email, :password, :password_confirmation
甚至尝试过设置
config.active_record.whitelist_attributes = false
然而,在命令行上仍然有相同的结果。
有什么技巧可以让我的数据库填充示例用户吗?
非常感谢。
添加
attr_accessible :name
到模型。目前,您只有:user_name
(和其他值)可访问。
只需将authentication_token添加到attr_accessible 例如:我收到的错误
Media1s-Mac-mini:rails_apps media1$ rake clipsfree_import RAILS_ENV=发展 csvfile=/Users/media1/Desktop/clips/atemp5/demotracks2/import.csv rake 中止!无法批量分配受保护的属性:标题 /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.11/lib/active_model/mass_assignment_security/sanitizer.rb:48:in process_removed_attributes' /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.11/lib/active_model/mass_assignment_security/sanitizer.rb:20:indebug_protected_attribute_removal' /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.11/lib/active_model/mass_assignment_security/sanitizer.rb:12:in 消毒' /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activemodel-3.2.11/lib/active_model/mass_assignment_security.rb:230:insanitize_for_mass_assignment'/usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.11/lib/active_record/attribute_assignment.rb:75:in assign_attributes' /usr/local/rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.11/lib/active_record/base.rb:497:ininitialize' /users/media1/Desktop/rails_apps/lib/tasks/clipsfree_import.rake:14:in 新' /Users/media1/Desktop/rails_apps/lib/tasks/clipsfree_import.rake:14:inblock (2 级)在 ' /users/media1/Desktop/rails_apps/lib/tasks/clipsfree_import.rake:5:in 每个' /Users/media1/Desktop/rails_apps/lib/tasks/clipsfree_import.rake:5:inblock 在 ' 任务中: TOP => clipsfree_import (通过运行任务查看完整跟踪 与 --跟踪)
解决方案:在 loopsfree.rb 的 models 文件夹中添加了要attr_accessible的属性标题
class Loopsfree < ActiveRecord::Base attr_accessible :ISRC, :title, :artist, :bpm, :file_name, :genre, :id, :sub_genre end
希望这对:)有所帮助快乐编码