dev
dev

Reputation: 392

RoR ActiveRecord save method

Im new to Rails, im trying to execute the save method within an ActionController's Create method multiple times to insert multiple values

def create

  @pin = Pin.new(params[:pin])
  i = 1

  while i < 10
    if @pin.save
    end
  end

  redirect_to @pin

end

This works but only inserts one record there's no Contraints that enforces uniqueness of Records in my Database. Please how do i correct this?

Upvotes: 0

Views: 202

Answers (2)

Anatoly
Anatoly

Reputation: 15530

you should extend your resource with create_multiple method and send params as array, see the details here

Upvotes: 0

bassneck
bassneck

Reputation: 4043

One AR objects maps to one row. You need to create new object for each row you want added.

Something like that:

10.times do
  pin = Pin.new(params[:pin])
  pin.save
end

or

10.times do 
  Pin.create(params[:pin]
end

create method creates an AR object and saves it in the database. However, you cannot redirect to 10 objects.

Upvotes: 3

Related Questions