Rails 销毁 has_one 关联上的上传
Rails destroys upload on has_one association
我有一个带有关联的组织模型 has_one :uploads, as: :uploadable
与
的多态关系
class Upload < ApplicationRecord
include Uploaders::StandardUploader::Attachment.new(:file)
belongs_to :uploadable, polymorphic: true, touch: true, optional: true
end
在创建记录方面一切正常,但是当我编辑时:
= form.fields_for :upload, organization.upload do |form_upload|
= form_upload.label :file
= form_upload.file_field :file
span Choose file...
controller在edit方法中调用build_upload
,建立一个新的association,实际上是销毁已有的association
如果我不调用 build_upload
,表单上传字段为空。
我对发生的事情一头雾水...我该怎么做才能防止 has_one
上的破坏,从而不会丢失现有的上传内容?
如何确保表单填写现有上传?
尝试像这样设置关联
has_one :uploads, as: :uploadable, autosave: false
您应该启用 nested attributes 以允许通过父记录更新关联记录:
class UploadableModel < ApplicationRecord
# ...
accept_nested_attributes_for :upload
end
fields_for
应该会自动生成 ActiveRecord 期望的嵌套属性格式的表单字段。请参阅下面 fields_for
API 文档中的示例。
我有一个带有关联的组织模型 has_one :uploads, as: :uploadable
与
的多态关系class Upload < ApplicationRecord
include Uploaders::StandardUploader::Attachment.new(:file)
belongs_to :uploadable, polymorphic: true, touch: true, optional: true
end
在创建记录方面一切正常,但是当我编辑时:
= form.fields_for :upload, organization.upload do |form_upload|
= form_upload.label :file
= form_upload.file_field :file
span Choose file...
controller在edit方法中调用build_upload
,建立一个新的association,实际上是销毁已有的association
如果我不调用 build_upload
,表单上传字段为空。
我对发生的事情一头雾水...我该怎么做才能防止 has_one
上的破坏,从而不会丢失现有的上传内容?
如何确保表单填写现有上传?
尝试像这样设置关联
has_one :uploads, as: :uploadable, autosave: false
您应该启用 nested attributes 以允许通过父记录更新关联记录:
class UploadableModel < ApplicationRecord
# ...
accept_nested_attributes_for :upload
end
fields_for
应该会自动生成 ActiveRecord 期望的嵌套属性格式的表单字段。请参阅下面 fields_for
API 文档中的示例。