1
I have a relationship like that 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 time, I urge several aliquots within the reduction
aliquota = reucao.aliquotas.build
aliquota.basecalculo = aliquota.valor
# outros valores
red.aliquotas << aliquota
and when I try to save z reduction, the field reducaoz_id
is not there. as there is a constraint to not save aliquot without reducaoz_id, activerecord throws an error.
Apparently it’s all right, I can’t see the error. Does anyone have any idea what I missed?
Edit The sql that 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
The question is not clear enough for me. Can’t you give more details? Copy the Activerecord error here.
– user7261
What happens is that Rails is not setting the reduction in aliquot, making the relationship between them. The bank won’t let you save an aliquot without a reduction. I added SQL to the question
– Luiz E.
The reduction already exists in the database?
– GuiGS
not yet. the
red.save!
saves reduction and then aliquots, but aliquots come without reduction id. The funny thing is that other models do the same thing (Invoice -> items) and I can save them without problems– Luiz E.