Skip to main content
 首页 » 编程设计

ruby-on-rails之如何在 rails (4.1.5) 中创建装置(对于设计用户)作为 yml.erb

2025年01月19日14xxx_UU

更新 3 :这似乎是特定于 .yml.erb 中的装置 - 即使我没有模板化代码,似乎也没有加载 yml.erb 文件中的装置。拥有一个普通的 .yml 文件。这可能与设计本身无关。

注意:有关相关更改,请参阅更新 3 注释

我需要在我的 rails 应用程序中生成设计用户。我注意到清除数据库并加载设备会加载所有其他设备,除了 Devise 用户( 更新 3 :在 .yml.erb 文件中)。

我见过this other thread ,但我尝试了那里的所有选项,但似乎仍然没有加载灯具。

# ../fixtures/users.yml.erb 
user1: 
  email: user1@mysite.com 
  name: user1 
  encrypted_password: <%= Devise.bcrypt(User, 'passw0rd!') %> 
  # also tried encrypted_password: User.new(password_salt: '$2a$10$PoBe1MvkoGJsjMVTEjKqge').send(:password_digest, 'somepassword') 
  admin: true 

从控制台:

清除测试数据库:
$ bundle exec rake db:schema:load RAILS_ENV=test 

将夹具加载到测试数据库中:
$ bundle exec rake db:fixtures:load RAILS_ENV=test 

在测试中运行 rails 控制台(未找到用户,但正在加载其他模型装置,如 App):
$ rails c test 
Loading test environment (Rails 4.1.5) 
irb(main):001:0> User.first 
  User Load (0.1ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1 
=> nil 
irb(main):002:0> App.first 
  App Load (0.1ms)  SELECT  "apps".* FROM "apps"   ORDER BY "apps"."id" ASC LIMIT 1 
=> #<App id: 953336129,...> 

更新 1 : 也试过传入从控制台生成的加密密码,仍然没有找到用户记录:
admin: 
  email: user1@mysite.com 
  name: user1 
  encrypted_password: $2a$04$DR0.2yfWwD8AZlyeXx0gEuk2Qh.cNLF4cir0ZUB1iW7hwQhK/IfcC 
  admin: true 

更新 2 :当我将fixtures 文件重命名为users.yml 时它会起作用。重命名为 users.yml.erb 似乎是罪魁祸首。顺便说一句,在控制台和 rake test 上看到了相同的行为(即,它适用于 .yml,但不适用于 yml.erb)。

请您参考如下方法:

您也应该以纯文本形式传递密码。我确信存在用户模型验证错误阻止您的设备用户被创建。这是我的用户装置中的一个示例,该示例有效:

tom: 
  first_name: Tom 
  last_name: Test 
  email: test@example.org 
  password: 123greetings 
  encrypted_password: <%= User.new.send(:password_digest, '123greetings') %> 

如果仍然失败,请查看 log/test.log文件错误并检查您在用户模型中设置的缺少的必填字段或其他验证规则。

更新:
事实证明,作者自己发现了这个问题——使用了 .yml.erb 文件扩展名而不是 .yml,这使得 rails 绕过了该装置文件。 ERB 在 yml 夹具中工作,因为 rails 在解析它之前通过 ERB 运行夹具文件。