activerecord不保存关系

时间:2014-05-22 19:57:59

标签: ruby-on-rails activerecord ruby-on-rails-4

我有两个这样的课程

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

在某个时间内,我向Aliquota

添加了ReudcaoZ
aliquota = reucao.aliquotas.build
aliquota.basecalculo = aliquota.valor
# other stuff
red.aliquotas << aliquota

当我尝试保存记录时,似乎aliquota缺少对reducaoz的引用

这是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
我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

我认为问题在于它不知道Aliquota中用于链接2个类的主键是什么。试试这个。

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

通常,如果我必须指定class_name,我也会明确设置primaryforeign键,以便清晰明了。

来自你的评论

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

什么是red

reducao定义在哪里?

管道al已经格式化Aliquota

否则我需要更多代码,因为我看不到被引用的对象。

修改 - 在评论中进一步澄清后

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 

首先保存reducao,如果它通过验证然后build保存aliquota,则会因为build方法而立即关联,因此无需重新保存reducao