我有一个包含5个水果的用户模型:
User
fruit_1
fruit_2
fruit_3
fruit_4
fruit_5
插入用户模型时是否可以执行for-each?像
@fruits = ['apple','banana','orange','strawberry','blueberry']
user = User.new
@fruits.each do |a, fruit |
user.fruit_a = fruit <-- I want a to be the actual variable.
end
答案 0 :(得分:3)
@fruits.each_with_index do |fruit, i|
attrib = "fruit_#{i + 1}"
user.send(attrib) = fruit
end
答案 1 :(得分:1)
如果您需要,可以使用以下语法:
user.assign_attributes(Hash[1.upto(@fruits.length).map{|i| ["fruit_#{i}", fruit[i]]}])