在保存模型之前,我有一个模型需要基于has_many :through
关联验证可访问性。类似这样的东西:
class Document < ActiveRecord::Base
belongs_to :organization
has_many :category_documents
has_many :categories, through: :category_documents
validate :categories_are_accessible_to_organization
private
def categories_are_accessible_to_organization
if (organization.category_ids & category_ids) != category_ids
errors.add(:categories, "not accessible to the parent organization")
end
end
end
在新唱片上似乎没有问题。但是,对于持久化记录,如果验证失败,则更新期间添加的类别将持久化。有没有办法推迟这些连接模型的持久性,直到Document
对象通过验证并通过任何内置机制保存?
为了检查关联的有效性,您可以使用validates_associated :categories
,请参阅链接-1和链接-2。
为了检查Document
的验证,您可以在更新操作的documents_controller.rb
中执行以下操作:
def update
@document.attributes = document_params
respond_to do |format|
if @document.valid? && @document.update(document_params)
format.html { redirect_to documents_path, notice: 'Document was successfully updated.' }
else
format.html { render action: 'edit' }
end
end
end
我的想法是,在保存任何关联对象之前,您使用活动记录的属性来检查验证。
您可以通过将验证移动到联接模型(即CategoryDocument
)来实现相同的目标,类似于
class CategoryDocument < ActiveRecord::Base
belongs_to :category
belongs_to :document
before_save do
false unless document.organization.category_ids.include?(category.id)
end
end
这将使像这样的操作失败
Document.first.categories << category_that_does_not_satisfy_validation # raises ActiveRecord::RecordNotSaved