Reputation: 7166
I have a user model with 5 fruits:
User
fruit_1
fruit_2
fruit_3
fruit_4
fruit_5
Is it possible to do a for-each when inserting into the user model? Like
@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
Upvotes: 0
Views: 44
Reputation: 6346
Here's an alternate syntax if you want:
user.assign_attributes(Hash[1.upto(@fruits.length).map{|i| ["fruit_#{i}", fruit[i]]}])
Upvotes: 1
Reputation: 27789
@fruits.each_with_index do |fruit, i|
attrib = "fruit_#{i + 1}"
user.send(attrib) = fruit
end
Upvotes: 3