Ruby on rails 在Rails中验证的计数有很多关系
我已经问过其他问题,但这里的情况没有什么不同:Ruby on rails 在Rails中验证的计数有很多关系,ruby-on-rails,rails-activerecord,polymorphic-associations,Ruby On Rails,Rails Activerecord,Polymorphic Associations,我已经问过其他问题,但这里的情况没有什么不同: 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.docu
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
。在数据库中创建文档后,user
和document.last
都无效,但是出于什么用途,现在已经创建了它们
我试图在运行时创建一个
文档
对象,这可能是原因,但为此,我在验证中使用了大小
,而不是计数。您可以使用标准验证,而不是自定义验证:
validates :documents, length: { maximum: 2 }
您可以将其打包到事务中,尽管我有点惊讶,如果文档保存无效,它不会正确回滚文档保存 逆
再次在此施救
user = User.find(1) # This user has already 2 associated documents.
执行user.documents如果将if self.documents.size>2
设置为if self.documents.size>1
,它将停止为同一用户创建第三个文档。用户的验证方法在创建文档
之前触发。您是否尝试将验证\u关联:用户
放入文档中。rb
?@Pavan验证\u关联:用户
不会在文档
中工作以获得多态性可附加性”
user`将是未定义的。@Arslan:嘿,你有没有找到解决这个问题的好办法?@kiddorails:有,我有一个,并已将其作为答案发布。
user = User.find(1) # This user has already 2 associated documents.
# In User model
has_many :documents, as: :attachable, inverse_of: :attachable
# In Document model
belongs_to :attachable, polymorphic: true, inverse_of: :attachments