activerecord is not saving the relationship

1

I have such a relationship in rails

class ReducaoZ < ActiveRecord::Base
  self.table_name = 'reducaoz'   
  has_many :aliquotas, foreign_key: 'reducaoz_id', class_name: 'Aliquota', dependent: :delete_all
end


class Aliquota < ActiveRecord::Base
  self.table_name = 'aliquota'

  belongs_to :reducaoz, class_name: 'ReducaoZ'
end

And at a given moment, I instantiate several aliquots within the reduction

aliquota = reucao.aliquotas.build
aliquota.basecalculo = aliquota.valor
# outros valores
red.aliquotas << aliquota

and when I try to save the z reduction, the reducaoz_id field is not there. as there is a restriction to not saving aliquot without reduction_id, activerecord throws an error.
apparently everything is correct, I can not see the error. Anyone have any idea what I missed?

Edit The sql that the rails tries to execute (along with the error) is this

  SQL (23.4ms)  INSERT INTO "aliquota" ("aliquota", "basecalculo", "valor") VALUES ($1, $2, $3) RETURNING "id"  [["aliquota", "0300"], ["basecalculo", "0.0"], ["valor", "0.0"]]
PG::NotNullViolation: ERROR:  null value in column "reducaoz_id" violates not-null constraint
: INSERT INTO "aliquota" ("aliquota", "basecalculo", "valor") VALUES ($1, $2, $3) RETURNING "id"
   (1.0ms)  ROLLBACK
ActiveRecord::StatementInvalid Exception: PG::NotNullViolation: ERROR:  null value in column "reducaoz_id" violates not-null constraint
    
asked by anonymous 22.05.2014 / 16:11

1 answer

1
  

PG :: NotNullViolation: ERROR: null value in column "reducaoz_id" violates not-null constraint

The PG in front of the exception tells us that this exception was raised by Postgres (because of the constraint NOT NULL ) and not directly by ActiveRecord. This means that you forgot to add

validates :reducaoz_id, presence: true

But this does not solve your problem.

Try changing once

aliquota = reucao.aliquotas.build

by

@reducao = ReducaoZ.find(params[:reducaoz_id]) # esta linha pode mudar (não sei como tu fez)
@aliquota = @reducao.aliquotas.new

Though theoretically the same thing.

    
23.05.2014 / 14:33