我想知道是否有更简洁的方法来验证rails中的多个关系。我并不是指验证一个关联,而是确保两个或多个belongs_to关联之间的关系完整性。以下是一些代码示例:
class User < ActiveRecord::Base
has_many :products, inverse_of: :user
has_many :purchases, inverse_of: :user
end
class Purchase < ActiveRecord::Base
belongs_to :user, inverse_of: :purchases
has_many :products, inverse_of: :purchase
end
class Product < ActiveRecord::Base
belongs_to :user, inverse_of: :products
belongs_to :purchase, inverse_of: :products
validates :user, :purchase, presence: true
validate :purchase_user
private
def purchase_user
errors.add(:purchase, 'purchase user does not match user') if user != purchase.user
end
end
purchase_user
验证方法会检查user
是否与purchase.user
相同,如果不是,则会添加错误。
我可以将其更改为使用:inclusion
,如下所示:
validates :purchase, inclusion: { in: proc { |record| record.user.purchases } }
但这似乎效率更低,有什么建议吗?