非常具体的 ActiveRecord 验证
A Very Specific ActiveRecord Validation
我会尽力解释我的困境。
我有2个模型
用户和设备
设备有类型列。例如,它可以是平板电脑或智能 Phone.
然后我有另一个模型所有权
此模型同时属于用户和设备,因此它将在 table 匹配用户和设备的条目中表示该用户拥有该设备。
我需要在 Ownership 模型上设置一些验证,主要的开始。
- 任何设备都不能拥有超过一个所有权条目(就像验证 device_id 列是唯一的一样简单)
- 对于每种可用的设备类型,用户只能拥有一台设备。
那么我将如何对最后一部分进行验证?我无法将 client_id table 设置为唯一,因为它们将针对不同类型的设备设置多个条目。但我希望它们每种类型的设备只有一行。
我希望这是有道理的。如果您需要更多详细信息,请告诉我。我将不胜感激任何见解!
谢谢!
validates :device_id, uniqueness: true
validate :device_type_unique?
def device_type_unique?
if Ownership.includes(:device).where('devices.type = ? AND ownerships.user_id = ?', self.device.type, self.user_id)
errors.add(:user_id, "Can only own one device type.")
end
end
我会尽力解释我的困境。
我有2个模型 用户和设备
设备有类型列。例如,它可以是平板电脑或智能 Phone.
然后我有另一个模型所有权
此模型同时属于用户和设备,因此它将在 table 匹配用户和设备的条目中表示该用户拥有该设备。
我需要在 Ownership 模型上设置一些验证,主要的开始。
- 任何设备都不能拥有超过一个所有权条目(就像验证 device_id 列是唯一的一样简单)
- 对于每种可用的设备类型,用户只能拥有一台设备。
那么我将如何对最后一部分进行验证?我无法将 client_id table 设置为唯一,因为它们将针对不同类型的设备设置多个条目。但我希望它们每种类型的设备只有一行。
我希望这是有道理的。如果您需要更多详细信息,请告诉我。我将不胜感激任何见解!
谢谢!
validates :device_id, uniqueness: true
validate :device_type_unique?
def device_type_unique?
if Ownership.includes(:device).where('devices.type = ? AND ownerships.user_id = ?', self.device.type, self.user_id)
errors.add(:user_id, "Can only own one device type.")
end
end