Luiz E.
Luiz E.

Reputation: 7229

activerecord not saving a relation

I have two classes like this

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

in a certain time, I add an Aliquota to a ReudcaoZ

aliquota = reucao.aliquotas.build
aliquota.basecalculo = aliquota.valor
# other stuff
red.aliquotas << aliquota

and when I try to save the record, seems like the aliquota is missing his reference to reducaoz

this is the SQL

  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

am I missing something?

Upvotes: 0

Views: 368

Answers (1)

engineersmnky
engineersmnky

Reputation: 29308

I think the issue is that it does not know what the primary key in Aliquota is for linking the 2 classes. try this.

class ReducaoZ < ActiveRecord::Base
  self.table_name = 'reducaoz'   
  has_many :aliquotas, primary_key: 'id', 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', primary_key: 'reducaoz_id', foreign_key: 'id'
end

Generally if I have to specify class_name I will explicitly set the primary and foreign keys as well for clarity.

from your comment

json_data.aliquotas_list.each_with_index do |al, index|
  aliquota = reducao.aliquotas.build
  # populate aliquota
  red.aliquotas << aliquota
end
red.save!

what is red?

where is reducao defined?

Also is the piped al already a formatted Aliquota?

Otherwise I need a bit more code since I cannot see the objects being referenced.

Edit -After further clarification in comment

reducao = ReducaoZ.new
if reducao.save
  json_data.aliquotas_list.each_with_index do |al, index|
    aliquota = reducao.aliquotas.build
    # populate aliquota
    aliquota.save
  end
end 

Save reducao first and if it passes validation then build the aliquota(s) on save they will immediately be associated because of the build method so no need to resave reducao.

Upvotes: 1

Related Questions