I have a pretty simple set of data requirements to do with pets and veterinarians.
我对宠物和兽医有一套非常简单的数据要求。
- An
owner
can have manypets
- 主人可以养很多宠物
- A
pet
can have oneowner
- 宠物可以拥有一个主人
- A
pet
can be treated by (belongs_to) manyveterinarians
- 宠物可以由(belongs_to)许多兽医治疗
- A
veterinarian
can treat (have_many)pets
- 兽医可以治疗(有很多)宠物
Owner
and Veterinarian
are both subclasses of User
using STI.
所有者和兽医都是使用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 Pet
s, Pet
belongs_to :owner and Pet
has_and_belongs_to_many Veterinarian
s?
失败发生在最后一行。事实证明,o.veterinarians只有1条记录。我知道宠物不是传统意义上的连接桌,因为每次我在主人和兽医之间建立关系时我都不想创造一个全新的宠物。我是否应该使用更像所有者has_many Pets,Pet belongs_to:owner和Pet has_and_belongs_to_many兽医?
Thanks!
谢谢!
1 个解决方案
#1
1
You have to use a join table between the Pet
and the Veterinarian
. Let's call it Treatment
:
您必须在宠物和兽医之间使用连接表。我们称之为治疗:
class Treatment < ...
...
belongs_to :pet
belongs_to :veterinarian
...
end
class Veterinarian < ...
...
has_many :treatments
has_many :pets, through: :treatments
...
end
class Pet < ...
...
has_many :treatments
has_many :veterinarians, through: :treatments
...
end
#1
1
You have to use a join table between the Pet
and the Veterinarian
. Let's call it Treatment
:
您必须在宠物和兽医之间使用连接表。我们称之为治疗:
class Treatment < ...
...
belongs_to :pet
belongs_to :veterinarian
...
end
class Veterinarian < ...
...
has_many :treatments
has_many :pets, through: :treatments
...
end
class Pet < ...
...
has_many :treatments
has_many :veterinarians, through: :treatments
...
end