Ruby on Rails - 无法在模型中存储哈希数组

时间:2012-06-27 23:07:36

标签: ruby-on-rails ruby json

我正在创建一个哈希数组并通过json将它传递给控制器​​。这是我发送的数据和一些服务器输出:

Started POST "/api/user.json" for 127.0.0.1 at Wed Jun 27 18:52:32 -0400 2012
  Processing by Api::UsersController#create as JSON
  Parameters: {"accept"=>"json", "content_type"=>"json", "users"=>"[{\"email\":\"kirsten_gronberg@yahoo.com\"},{\"email\":\"dtsheahan@msn.com\"},{\"email\":\"clayton19361@hotmail.com\"},{\"email\":\"kumar.alka92@yahoo.com\"},{\"email\":\"j.eromes.n.d.c@gmail.com\\r\"},{\"email\":\"0\"},{\"email\":\"christine@colormepink.com\"},{\"email\":\"janabouc@gmail.com\"},{\"email\":\"carin@inkfoundry.com\"},{\"email\":\"jon.neiditz@nelsonmullins.com\"}]"}

这是我的控制器代码:

参与["用户"]。每个{| user_params |   User.create!(user_params) }

这是错误:

Completed 500 Internal Server Error in 2ms

NoMethodError (undefined method `keys' for #<String:0x10662d660>):
  app/controllers/api/users_controller.rb:6:in `create'
  app/controllers/api/users_controller.rb:5:in `each'
  app/controllers/api/users_controller.rb:5:in `create'

有人会在这里知道我可能会遇到什么问题吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

当您收到params[:users]时,您实际上是在接收字符串而不是哈希。这个字符串恰好用JSON编码(即采用带有Ruby哈希相似的样式。)您必须通过hash = JSON.parse(params[:users])等方法将此字符串转换为哈希值。