0

我有一个有 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
4

2 回答 2

3
@fruits.each_with_index do |fruit, i|
  attrib = "fruit_#{i + 1}"
  user.send(attrib) = fruit
end
于 2013-05-31T20:24:40.653 回答
1

如果您愿意,这是另一种语法:

user.assign_attributes(Hash[1.upto(@fruits.length).map{|i| ["fruit_#{i}", fruit[i]]}])
于 2013-05-31T20:41:33.583 回答