Rails-外键循环

时间:2016-10-03 23:02:53

标签: ruby-on-rails foreign-keys ruby-on-rails-5

我有两个模型,projectsingle_object_interactive

class SingleObjectInteractive < ApplicationRecord
  belongs_to :project
end

class Project < ApplicationRecord
  has_one :single_object_interactive
  accepts_nested_attributes_for :single_object_interactive
end

当我尝试创建project时,我收到一条错误消息single_object_interactive没有project

以下代码有效:

def create
  @project = Project.new(project_params)
  @project.single_object_interactive.project = @project
  @project.save

它有效,但它感觉破碎和循环。为什么项目single_object_interactive自动链接到项目?

更新

如果我在没有奇怪的@project.save!行的情况下致电@project.single_object_interactive.project = @project,则会出现错误消息:

(0.2ms)  ROLLBACK
*** ActiveRecord::RecordInvalid Exception: Validation failed: Single object interactive project must exist

nil

0 个答案:

没有答案