Dan
Dan

Reputation: 2313

A Very Specific ActiveRecord Validation

I'm will try to explain my dilemma as best I can.

I have a 2 models Users and Devices

Devices has a type column. For example it can be a Tablet or a Smart Phone.

I then have another model Ownership

This model belongs to both Users and Devices so it will have entries in the table matching users to devices representing that that user owns that device.

I need to setup some validations on the Ownership model the primary ones begin.

So how would I make a validation for this last part? I can't set the client_id table to unique because they will have multiple entries for different types of devices. But I want them to only have one row per type of device.

I hope this makes sense. Please let me know if you need more details. I would appreciate any insight!

Thanks!

Upvotes: 1

Views: 43

Answers (1)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

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

Upvotes: 1

Related Questions