我有一系列我试图在数据库中播种的哈希。
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']
如下所示:在Ruby中迭代一系列的哈希和这里:如何迭代一系列哈希并返回一个字符串中的值?
,但我仍然只得到无效的值。我如何将我的值纳入数据库?
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
根据文档,您可以从一系列哈希创建记录:
以下应该有效(您可以使用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})})
将迭代更改为
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
请注意,尽管您在数组上迭代两次,并且与第一个相比,效率也不太效率。
update
另一个选项是使用数组元素。
shoe_array.each do |attributes|
relationship = Relationship.new(attributes)
relationship.user_id = 1
relationship.save!
end