所以如果我有一个像这样的哈希数组:( ruby beginner)
input = [
{"last_name"=>"Gay", "first_name"=>"Rudy", "display_name"=>"Rudy Gay", "position"=>"SF", "minutes"=>39, "points"=>25, "assists"=>6},
{"last_name"=>"Collison", "first_name"=>"Darren", "display_name"=>"Darren Collison", "position"=>"PG", "minutes"=>39, "points"=>14, "assists"=>4}
]
我将如何遍历数组以及遍历每个哈希以获得类似的内容:
player1 = {display_name =>" rudy gay"," position" =>" SF"}
player2 = {display_name =>" darren collison"," position" =>" PG"}
会不会像
input.each do |x|
Player.create(name: x['display_name'], position: x['position']
end
(假设我有一个玩家模型)
有没有更好的方法来实现这一目标?
谢谢!
答案 0 :(得分:7)
鉴于您的意见:
input = [
{ "last_name"=>"Gay", ... },
{ "last_name"=>"Collison", ...}
]
如果Player
模型中存在所有这些键(last_name,first_name,display_name),您可以:
input.each do |x|
Player.create(x)
end
由于create
将使用要分配的属性哈希值。但是,更好的是,你甚至不需要迭代:
Player.create(input)
如果给它一个哈希数组,ActiveRecord将全部通过它们。