有没有一种简单的方法可以从具有多个关联中删除空白对象



我得到了以下模型:

class Course < ApplicationRecord
has_many :external_ids, as: :identifiable, dependent: :destroy, validate: true
accepts_nested_attributes_for :external_ids
end

这个:

class ExternalId < ApplicationRecord
belongs_to :identifiable, polymorphic: true
validates :name, presence: true, uniqueness: true
validates :identifiable, presence: true, on: :create
end

由于课程表单视图中存在嵌套表单,因此可能会保存外部id的空白对象。我想去掉这些空白的东西。用";空白对象";我指的是ExternalId,它是一个新记录,名称为空。目前我这样做如下:

@course.attributes = course_params
## SNIP - workaround to fix validations
external_ids = []
@course.external_ids.each do |ext_id|
external_ids << ext_id unless(ext_id.new_record? && ext_id.name.blank?)
end
@course.external_ids = external_ids
## SNAP - workaround to fix validations
@course.save

但这是一个非常简单的任务的大量代码。有什么功能吗?destroy_if不存在于关联中,仅存在于数组中。

谢谢!

您可以将accepts_nested_attributes_for与此类密钥一起使用

accepts_nested_attributes_for :external_ids, reject_if: proc { |attributes| attributes['name'].blank? }

来自文档:

如果任何新记录哈希未能通过您的标准,您也可以设置:reject_if进程以静默方式忽略它们

最新更新