【问题标题】:Validation for the count of has_many relationship in Rails验证 Rails 中 has_many 关系的计数
【发布时间】: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。在数据库中创建文档后,userDocument.last 都无效,但是现在已经创建了它们有什么用。

我试图在运行时创建一个Document 对象,这可能是导致它的原因,但为此,我在验证中使用size 而不是count

【问题讨论】:

  • 如果您将if self.documents.size &gt; 2 设置为if self.documents.size &gt; 1,它将停止为同一用户创建第三个文档。在创建Document 之前触发用户的验证方法
  • 您是否尝试将validates_associated :user 放入document.rb
  • @Pavan validates_associated :user 不会在 Document 中工作,因为多态 attachable'. user` 将是未定义的。
  • @Arslan :嘿,你有什么好的解决方案吗?
  • @kiddorails:是的,我得到了一个,并将其发布为答案。

标签: ruby-on-rails rails-activerecord polymorphic-associations


【解决方案1】:

inverse_of又来救援了。

user = User.find(1) # This user has already 2 associated documents. 

执行user.documents &lt;&lt; Document.new(file: file) 不会更改用户关联文档的计数,除非实际创建了文档,并且由于在创建第三个文档时计数将保持为 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

【讨论】:

    【解决方案2】:

    您可以为此使用标准验证,而不是自定义验证:

    validates :documents, length: { maximum: 2 }
    

    你总是可以将它包装在一个事务中,虽然我有点惊讶它没有正确回滚文档保存,如果它最终不是有效的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2013-01-10
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多