有时,您想为不同的关联使用不同的名称。如果您要用于模型上的关联的名称与模型上的关联不同:through
,您可以使用:source
来指定它。
我不认为上面的段落比文档中的更清晰,所以这里有一个例子。假设我们有三个模型Pet
,Dog
和Dog::Breed
。
class Pet < ActiveRecord::Base
has_many :dogs
end
class Dog < ActiveRecord::Base
belongs_to :pet
has_many :breeds
end
class Dog::Breed < ActiveRecord::Base
belongs_to :dog
end
在这种情况下,我们选择了命名空间 the Dog::Breed
,因为我们希望Dog.find(123).breeds
作为一个很好且方便的关联来访问。
现在,如果我们现在想在 上创建一个has_many :dog_breeds, :through => :dogs
关联Pet
,我们突然遇到了一个问题。Rails 将无法在 上找到:dog_breeds
关联Dog
,因此 Rails 不可能知道您要使用哪个关联。 Dog
输入:source
:
class Pet < ActiveRecord::Base
has_many :dogs
has_many :dog_breeds, :through => :dogs, :source => :breeds
end
使用:source
,我们告诉 Rails寻找模型:breeds
上Dog
调用的关联(因为那是用于 的模型:dogs
),并使用它。