如何解决has_one /通过关联问题?

时间:2019-05-29 17:01:33

标签: ruby-on-rails

我正在研究一个新项目。我的数据结构: -审计 -动作 -Reponses

审核由行动组成。 每个动作有一个响应。 每个响应都引用一个动作和一个审核。

审核

class Audit < ApplicationRecord

  belongs_to :entreprise
  has_many :reponse
  has_many :action, through: :reponse

  validates :numero, presence: true, uniqueness: true

end

操作

class Action < ApplicationRecord

  has_one :reponse
  has_many :audits, through: :reponse

  validates :numero, :titre, presence: true, uniqueness: true
  validates :description, :kpi, :priority, :scale, :effectSocial, :effectEnvironmental, :effectFinancial, :impactCC, :impactD, :impactE, :impactRNN, presence: true

end

回复

class Reponse < ApplicationRecord

  belongs_to :audit
  belongs_to :action

end

我认为我已经很接近了,但是当我启动rails console时,请添加一些数据并尝试使用以下命令添加回复:

Action.first.create_reponse(etat: "fine", kpi: 2, commentaire: "")

我明白了:

Action Load (2.0ms)  SELECT  "actions".* FROM "actions" ORDER BY "actions"."id" ASC LIMIT ?  [["LIMIT", 1]]
   (0.5ms)  begin transaction
   (0.1ms)  rollback transaction
  Reponse Load (0.2ms)  SELECT  "reponses".* FROM "reponses" WHERE "reponses"."action_id" = ? LIMIT ?  [["action_id", 1], ["LIMIT", 1]]
 => #<Reponse id: nil, commentaire: "", etat: "fine", kpi: 2, created_at: nil, updated_at: nil, action_id: 1, audit_id: nil> ```

1 个答案:

答案 0 :(得分:0)

如果一个对象属于另一个对象,则需要该对象的ID。因此,在您的情况下,响应将需要audit_id和action_id。

当您尝试创建响应时,它失败了,因为它没有audit_id。您的两个选择是将一个添加到创建响应的行中:

Action.first.create_reponse(etat: "fine", kpi: 2, commentaire: "", audit_id: Audit.first.id)

或者将您的belongs_to更改为belongs_to, required: false。这样一来,您可以保存不带审计ID的响应,但是,鉴于您如何布置数据,看来您想加强这种关系并采用第一种选择。

相关问题