Validation for the count of has_many relationship in Rails -
i have been through other questions, scenario little different here:
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 more 2") if self.documents.size > 2 end end class document < applicationrecord belongs_to :attachable, polymorphic: true validates_associated :attachable end
now, consider user.find(2)
has 2 documents, doing following:
user.documents << document.new(file: file.open('image.jpg', 'rb'))
this creates document, , doesn't validate attachable: user
. after document created in database, both user
& document.last
invalid, of use, have been created now.
i'm trying create document
object on run time, , may causing it, purpose, i'm using size
instead of count
in validation.
inverse_of
rescue here again.
user = user.find(1) # user has 2 associated documents.
doing user.documents << document.new(file: file)
won't change count associated documents of user unless document created, , since count remain 2 while creating 3rd document, rails won't stop creating third document associated user, killing purpose of putting validation.
so following did:
# in user model has_many :documents, as: :attachable, inverse_of: :attachable # in document model belongs_to :attachable, polymorphic: true, inverse_of: :attachments
related article read: https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through
Comments
Post a Comment