【发布时间】:2017-09-11 01:41:58
【问题描述】:
我也遇到过其他问题,但这里的情况略有不同:
class User < ApplicationRecord
has_many :documents, as: :attachable
validate :validate_no_of_documents
private
def validate_no_of_documents
errors.add(:documents, "count shouldn't be more than 2") if self.documents.size > 2
end
end
class Document < ApplicationRecord
belongs_to :attachable, polymorphic: true
validates_associated :attachable
end
现在,考虑已经有两个文档的User.find(2),因此执行以下操作:
user.documents << Document.new(file: File.open('image.jpg', 'rb'))
这成功地创建了文档,并且不验证可附加的:User。在数据库中创建文档后,user 和Document.last 都无效,但是现在已经创建了它们有什么用。
我试图在运行时创建一个Document 对象,这可能是导致它的原因,但为此,我在验证中使用size 而不是count。
【问题讨论】:
-
如果您将
if self.documents.size > 2设置为if self.documents.size > 1,它将停止为同一用户创建第三个文档。在创建Document之前触发用户的验证方法 -
您是否尝试将
validates_associated :user放入document.rb? -
@Pavan
validates_associated :user不会在Document中工作,因为多态attachable'.user` 将是未定义的。 -
@Arslan :嘿,你有什么好的解决方案吗?
-
@kiddorails:是的,我得到了一个,并将其发布为答案。
标签: ruby-on-rails rails-activerecord polymorphic-associations