Alexandre Gueths Alexandre Gueths - 5 months ago 14
Ruby Question

Creating multiple objects of same model in Rails

I want to create multiples objects of a same model in Rails and I'm facing some problems saving them. I already add and remove fields dynamically, but I can't figure out how to save the multiples objects.

I'm receiving the data from my View like this:

Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"0aoRgalvZPKdBJr15EooxNCimh2C6R2RBYi3wTXTpaIwpzb8cNSAH/968932KFscg8eiNPej1x2iYFsaWalVQw==",
"transaction"=>{
"client_id"=>"206",
"invoice_id"=>"1",
"date"=>"07/07/2016",
"value"=>"50",
"description"=>""},
"dates"=>[
"07/08/2016",
"07/09/2016"],
"values"=>[
"49",
"48"],
"commit"=>"Save"}


transaction
is the main transaction,
dates
and
values
are what difers from the main transaction and the other two transactions.

My create method in TransactionController is like this:

def create
@transaction = Transaction.new(transaction_params)
dates = params['dates']
values = params['values']
if(!dates.nil?)
@transactions_ = []
dates.length.times do |i|
t = Trasanction.create(
client_id: @transaction.client_id,
invoice_id: @transaction.invoice_id,
description: @transaction.description,
date: dates[i],
value: values[i])
@transactions_ << t
end
end
respond_to do |format|
if @transaction.save
@transactions_.each do |t|
t.save
end
format.html { redirect_to @transaction, notice: 'Transaction succefully created.' }
format.json { render :show, status: :created, location: @transaction }
else
format.html { render :new }
format.json { render json: @transaction.errors, status: :unprocessable_entity }
end
end
end


But I'm getting this error:

uninitialized constant TransactionsController::Trasanction
t = Trasanction.create(


Apparently I can't call
Transaction.create
that way, but I'm almost sure I saw something like that on a tutorial.

Answer

I see there is a mistake in your class name. It should be

Transaction.create({})

but, you are referring to it as

Trasanction.create({})

Just change the class name and it should work.