我有两个模型,project
和single_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