通过 Rails 了解 has_one/has_many 的 :source 选项 [英] Understanding :source option of has_one/has_many through of Rails
问题描述
请帮助我理解 has_one/has_many :through
关联的 :source
选项.Rails API 的解释对我来说意义不大.
Please help me in understanding the :source
option of has_one/has_many :through
association. The Rails API explanation makes very little sense to me.
"指定has_many
使用的源关联名称:through =>:查询
.仅当无法从名称中推断出名称时才使用它协会.has_many :subscribers, :through =>:subscriptions
将在 Subscription
上查找 :subscribers
或 :subscriber
,除非给出了 :source
."
"Specifies the source association name used by
has_many
:through => :queries
. Only use it if the name cannot be inferred from the association.has_many :subscribers, :through => :subscriptions
will look for either:subscribers
or:subscriber
onSubscription
, unless a:source
is given. "
推荐答案
有时,您希望为不同的关联使用不同的名称.如果您要用于模型上的关联的名称与 :through
模型上的关联不同,您可以使用 :source
来指定它.
Sometimes, you want to use different names for different associations. If the name you want to use for an association on the model isn't the same as the assocation on the :through
model, you can use :source
to specify it.
我不认为上面的段落比文档中的更清晰,所以这里有一个例子.假设我们有三个模型,Pet
、Dog
和 Dog::Breed
.
I don't think the above paragraph is much clearer than the one in the docs, so here's an example. Let's assume we have three models, Pet
, Dog
and 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
在这种情况下,我们选择为 Dog::Breed
命名空间,因为我们想访问 Dog.find(123).breeds
作为一个很好的和方便的关联.
In this case, we've chosen to namespace the Dog::Breed
, because we want to access Dog.find(123).breeds
as a nice and convenient association.
现在,如果我们现在想要创建一个 has_many :dog_breeds, :through =>
关联,我们突然遇到了一个问题.Rails 将无法在 Pet
上的:dogsDog
上找到 :dog_breeds
关联,因此 Rails 不可能知道 哪个 Dog代码>要使用的关联.输入
:source
:
Now, if we now want to create a has_many :dog_breeds, :through => :dogs
association on Pet
, we suddenly have a problem. Rails won't be able to find a :dog_breeds
association on Dog
, so Rails can't possibly know which Dog
association you want to use. Enter :source
:
class Pet < ActiveRecord::Base
has_many :dogs
has_many :dog_breeds, :through => :dogs, :source => :breeds
end
使用:source
,我们告诉Rails 在Dog
模型上寻找一个名为:breeds
的关联strong>(因为这是用于 :dogs
的模型),并使用它.
With :source
, we're telling Rails to look for an association called :breeds
on the Dog
model (as that's the model used for :dogs
), and use that.
这篇关于通过 Rails 了解 has_one/has_many 的 :source 选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!