Philip
Philip

Reputation: 7166

Variable when inserting into model

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

Answers (2)

Noz
Noz

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

Mori
Mori

Reputation: 27789

@fruits.each_with_index do |fruit, i|
  attrib = "fruit_#{i + 1}"
  user.send(attrib) = fruit
end

Upvotes: 3

Related Questions