阅读背景:

使用HMABTM验证所有权的最佳方法

来源:互联网 

I have three models like this:

我有三个这样的模型:

class User < ActiveRecord::Base
  has_many :items
  has_many :other_itmes
end

class Item < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :other_items

  validate :validate_other_item_ownership
  def validate_other_item_ownership
    if
      (user_ids = OtherItem.where(id: other_item_ids).pluck(:user_id).uniq).present? &&
        (user_ids.size > 1 || user_ids.first != user_id)
    then
      errors.add(:other_item_ids, 'Other Items must belong to same user as Item')
    end
  end
end

class OtherItem < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :items

  validate :validate_item_ownership
  def validate_item_ownership
    if
      (user_ids = Item.where(id: item_ids).pluck(:user_id).uniq).present? &&
        (user_ids.size > 1 || user_ids.first != user_id)
    then
      errors.add(:item_ids, 'Items must belong to same user as Other Item')
    end
  end
end
c



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: