Roland Studer
Roland Studer

Reputation: 4415

Problem: Cannot create mulitple table entries in an each-loop

I'm trying to loop through an array in my controller to create new users from an array of email-adresses

@emails.each do |email|
  @user = User.new(:email => email)
  @user.save
end

Now it always only creates one user and not the several the array actually contains.

I suspect, that I somehow have to reinitialize a new user differently as the controller will only handle on instance of it. What am I doing wrong?

Upvotes: 0

Views: 74

Answers (1)

idlefingers
idlefingers

Reputation: 32047

Are you sure it's only creating one user in the db? That code looks ok, but @user will only ever refer to a single instance because it will be re-set on each iteration through the array.

If you're wanting an array of users at the end, a better way of doing it would be to add them to an array (you could also use inject for this):

@users = []
@emails.each do |email|
  @users << User.create(:email => email)
end

Another reason could be due to validations making the record invalid. Do you have any validations on email? If you want to make it blow up if the record is invalid, use save or create with a bang (!)...

@emails.each do |email|
  User.create!(:email => email)
end

Upvotes: 2

Related Questions