Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails中验证的计数有很多关系_Ruby On Rails_Rails Activerecord_Polymorphic Associations - Fatal编程技术网

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