两个或多个belongs_to关联之间的AcriveRecord关系验证

时间:2015-10-04 10:06:10

标签: ruby-on-rails validation activerecord

我想知道是否有更简洁的方法来验证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 } }

但这似乎效率更低,有什么建议吗?

0 个答案:

没有答案