Wallace
Wallace

Reputation: 157

Ruby on Rails: How do you create a `has_one` relationship with duplicating primary keys?

I have 2 Tables:

Dogs
- id (primary key)

Cats
- id (primary key)

I would like to introduce a third table let's say Collars, that both dogs and cats have:

Collars:
- id (primary key)
- size

Typically if it was just Dog -> Collar model association, I could do a has_one relationship, and the default primary key id relationship would resolve.

class Dog < ActiveRecord:Base
  has_one :collar
end

dog.collar.size = "XL"

However, since I have 2 models (dogs and cats), I'm not sure how this association can resolve, since Dog and Cat tables can have duplicate id values. So the has_one relationship with the primary key falls apart.

class Dog < ActiveRecord:Base
  has_one :collar
end

class Cat < ActiveRecord:Base
  has_one :collar
end

# Dog Record - id: 1
# Cat Record - id: 1
# 2 separate tables allow for duplicate primary keys, so it would be impossible to resolve

dog.collar.size = "XL"
cat.collar.size = "S"

Is there a way to make this relationship work with active record associations?

Upvotes: 0

Views: 49

Answers (1)

Mittu Rajareddy
Mittu Rajareddy

Reputation: 21

just a suggestion: add size directly to dogs and cats table because it takes less space than a whole new table and less complex

here belongs_to can help you

Upvotes: 0

Related Questions