我有一系列哈希,我试图将其植入数据库。
shoe_array = [{:department_id=>8, :follower_id=>31}, {:department_id=>9, :follower_id=>41}, {:department_id=>4, :follower_id=>49}, {:department_id=>2, :follower_id=>58}, {:department_id=>5, :follower_id=>36}, {:department_id=>9, :follower_id=>63}, {:department_id=>2, :follower_id=>52}, {:department_id=>23, :follower_id=>26}, {:department_id=>5, :follower_id=>52}, {:department_id=>6, :follower_id=>30}]
shoe_array.each do |n, k|
department_id = n,
follower_id = k,
user_id = 1
Relationship.create!(department_id: department_id,
follower_id: follower_id,
user_id: user_id)
end
我只为department_id
和follower_id
获取空值。 user_id
正在运作。
我尝试使用"#{n}"
和"#{k}"
来获取设置为部门和关注者ID的键值。我还尝试仅使用.each do |a|
并设置department_id: a['department_id'], follower_id a['follower_id']
如此处所示:iterate through array of hashes in ruby和此处:How do I iterate over an array of hashes and return the values in a single string?
但我仍然只能获得空值。如何将我的值输入数据库?
答案 0 :(得分:2)
shoe_array
是一个散列数组,因此您应该迭代每个散列,并访问每个键值对:
shoe_array.each do |hash|
department_id = hash[:department_id]
follower_id = hash[:follower_id]
user_id = 1
Relationship.create!(
department_id: department_id,
follower_id: follower_id,
user_id: user_id
)
end
答案 1 :(得分:2)
根据文档,您可以create来自一系列哈希的记录:
以下应该可以使用(您可以使用create!
以及create
)
shoe_array = [{:department_id=>8, :follower_id=>31}, {:department_id=>9, :follower_id=>41}, {:department_id=>4, :follower_id=>49}, {:department_id=>2, :follower_id=>58}, {:department_id=>5, :follower_id=>36}, {:department_id=>9, :follower_id=>63}, {:department_id=>2, :follower_id=>52}, {:department_id=>23, :follower_id=>26}, {:department_id=>5, :follower_id=>52}, {:department_id=>6, :follower_id=>30}]
Relationship.create!(shoe_array.map{|arr| arr.merge!({user_id: 1})})
答案 2 :(得分:1)
将迭代更改为
shoe_array.each do |shoe|
department_id = shoe[:department_id]
follower_id = shoe[:follower_id]
可以使用|n, k|
的示例可以是散列或数组数组。如果你想沿着那条路走下去,你可以在数组中的每个哈希上调用values
(假设哈希是一致的,这意味着department_id
始终在follower_id
之前出现)
ids = shoe_array.map(&:values) # [[8, 31], [9, 41], [4, 49], [2, 58], [5, 36], [9, 63], [2, 52], [23, 26], [5, 52], [6, 30]]
然后您可以使用旧代码或重构
ids.each do |department_id, follower_id|
Relationship.create!(
department_id: department_id,
follower_id: follower_id,
user_id: 1
)
end
请注意,虽然您正在迭代数组两次,但与第一次相比效率会降低。
<强>更新强>
另一种选择是按原样使用数组元素。
shoe_array.each do |attributes|
relationship = Relationship.new(attributes)
relationship.user_id = 1
relationship.save!
end