204

请帮助我理解关联的:source选择has_one/has_many :through。Rails API 的解释对我来说意义不大。

“指定 . 使用的源关联名称has_many :through => :queries。仅在无法从关联中推断名称时使用它。除非给出 a,否则将在或上has_many :subscribers, :through => :subscriptions查找。”:subscribers:subscriberSubscription:source

4

3 回答 3

267

有时,您想为不同的关联使用不同的名称。如果您要用于模型上的关联的名称与模型上的关联不同:through,您可以使用:source来指定它。

我不认为上面的段落比文档中的清晰,所以这里有一个例子。假设我们有三个模型PetDogDog::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寻找模型:breedsDog调用的关联(因为那是用于 的模型:dogs),并使用它。

于 2011-01-08T05:12:17.397 回答
217

让我扩展这个例子:

class User
  has_many :subscriptions
  has_many :newsletters, :through => :subscriptions
end

class Newsletter
  has_many :subscriptions
  has_many :users, :through => :subscriptions
end

class Subscription
  belongs_to :newsletter
  belongs_to :user
end

使用此代码,您可以执行诸如Newsletter.find(id).users获取时事通讯订阅者列表之类的操作。但是,如果您想更清楚并能够键入Newsletter.find(id).subscribers,则必须将 Newsletter 类更改为:

class Newsletter
  has_many :subscriptions
  has_many :subscribers, :through => :subscriptions, :source => :user
end

您正在将users关联重命名为subscribers。如果您不提供,Rails 将查找在 Subscription 类:source中调用的关联。subscriber您必须告诉它使用userSubscription 类中的关联来制作订阅者列表。

于 2011-01-08T05:07:32.970 回答
16

最简单的答案:

是中间表中的关系名称。

于 2017-04-20T15:12:03.743 回答