我有两个通过has_many through
关联的实体,它们通过连接模型链接,执行一些验证。但是,当验证失败时,即使链接未持久存在,该对象也存在。我一定做错了......
class Aklass < ActiveRecord::Base
has_many :links
has_many :bklasses, through: :links
end
class Bklass < ActiveRecord::Base
has_many :links
has_many :aklasses, through: :links
end
class Link < ActiveRecord::Base
belongs_to :aklass
belongs_to :bklass
validate :fail_validation
def fail_validation
errors.add(:base, 'Always fails')
end
end
Rails控制台会话:
rails c
a = Aklass.new
b = Bklass.new
a.links
#<ActiveRecord::Associations::CollectionProxy []>
a.bklasses << b
(0.3ms) ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Always fails
a.links
#<ActiveRecord::Associations::CollectionProxy [#<Link id: nil, aklass_id: 1, bklass_id: 1>]>
我理解它不会持久化,因为验证失败了,但是关联对象的“闲逛”会使应用程序处于不一致状态,因为它允许查询a.links.first.bklass
之类的内容,这对于我,因为验证失败了......
我做错了什么?通过关联验证has_many的最佳实践是什么?