验证 Rails 中 has_many 关系的计数
Validation for the count of has_many relationship in Rails
我已经解决了其他问题,但这里的情况略有不同:
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
在我的验证中。
您可以为此使用标准验证,而不是自定义验证:
validates :documents, length: { maximum: 2 }
您总是可以将它包装在一个事务中,但我有点惊讶它没有正确回滚文档保存,如果它最终不是有效的。
inverse_of
又来救援了
user = User.find(1) # This user has already 2 associated documents.
执行 user.documents << Document.new(file: file)
不会更改用户关联文档的计数,除非实际创建文档,并且由于在创建第 3 个文档时计数将保持为 2,因此 Rails不会阻止您创建与用户关联的第三个文档,从而扼杀进行验证的目的。
下面是我所做的:
# In User model
has_many :documents, as: :attachable, inverse_of: :attachable
# In Document model
belongs_to :attachable, polymorphic: true, inverse_of: :attachments
要阅读的相关文章:https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through
我已经解决了其他问题,但这里的情况略有不同:
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
在我的验证中。
您可以为此使用标准验证,而不是自定义验证:
validates :documents, length: { maximum: 2 }
您总是可以将它包装在一个事务中,但我有点惊讶它没有正确回滚文档保存,如果它最终不是有效的。
inverse_of
又来救援了
user = User.find(1) # This user has already 2 associated documents.
执行 user.documents << Document.new(file: file)
不会更改用户关联文档的计数,除非实际创建文档,并且由于在创建第 3 个文档时计数将保持为 2,因此 Rails不会阻止您创建与用户关联的第三个文档,从而扼杀进行验证的目的。
下面是我所做的:
# In User model
has_many :documents, as: :attachable, inverse_of: :attachable
# In Document model
belongs_to :attachable, polymorphic: true, inverse_of: :attachments
要阅读的相关文章:https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through