1

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.

  • No device can have more than one ownership entry (simple as validating that device_id column is unique)
  • A user can only have ownership of one device for each type of device available.

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!

Dan
  • 2,299
  • 2
  • 20
  • 41
  • This sounds like you want validates uniqueness with a scope option. http://guides.rubyonrails.org/active_record_validations.html#uniqueness – John Naegle May 28 '15 at 03:01
  • That's what I was looking at earlier. But can that scope options be on a column in my Devices table? So I would have something like validates :user_id, uniqueness: { scope: :device_type??, message: "Can only own one device type." } – Dan May 28 '15 at 03:04

1 Answers1

1
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
Vrushali Pawar
  • 3,753
  • 1
  • 13
  • 22