I have a pretty simple set of data requirements to do with pets and veterinarians.
- An
ownercan have manypets - A
petcan have oneowner - A
petcan be treated by (belongs_to) manyveterinarians - A
veterinariancan treat (have_many)pets
Owner and Veterinarian are both subclasses of User using STI.
Here’s some code:
class Owner < User
has_many :pets
has_many :veterinarians, :through => :pets
end
class Veterinarian < User
attr_accessible :clinic_name
has_many :pets
has_many :owners, :through => :pets
end
class Pet < ActiveRecord::Base
attr_accessible :name, :date_of_birth, :species, :breed, :gender, :neutered
belongs_to :owner
belongs_to :veterinarian
end
And here is the spec that is failing:
it "has various veterinarians" do
o = Owner.make!(:email => 'owner1@gmail.com')
v1 = Veterinarian.make!(:email => 'vet_1@gmail.com')
v2 = Veterinarian.make!(:email => 'vet_2@gmail.com')
p = Pet.make!(:name => 'fluffy')
o.pets << p
v1.pets << p
v2.pets << p
o.pets.should have(2).records
o.veterinarians.should have(2).records
end
The make! stuff is to do with using machinist fixture replacement. It just factory creates the objects.
The failure occurs on the last line. It turns out that o.veterinarians only has 1 record. I understand that a pet is not a join table in the traditional sense, inasmuch as I don’t want to create a whole new pet each time I create a relationship between an owner and a veterinarian. Should I be using a schema more like Owner has_many Pets, Pet belongs_to :owner and Pet has_and_belongs_to_many Veterinarians?
Thanks!
You have to use a join table between the
Petand theVeterinarian. Let’s call itTreatment: