请帮助我理解has_one/has_many:通过关联的:source选项。Rails API的解释对我来说没什么意义。
has_many使用的源关联名称:through => :查询。仅当名称不能从 协会。Has_many:订阅者,:through =>:订阅将 寻找订阅者或订阅者 除非给出了a:来源。”
请帮助我理解has_one/has_many:通过关联的:source选项。Rails API的解释对我来说没什么意义。
has_many使用的源关联名称:through => :查询。仅当名称不能从 协会。Has_many:订阅者,:through =>:订阅将 寻找订阅者或订阅者 除非给出了a:来源。”
让我进一步解释一下这个例子:
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)的操作。用户可以获得时事通讯的订阅者列表。但如果你想更清楚,可以输入时事通讯。find(id)。相反,你必须将Newsletter类更改为:
class Newsletter
has_many :subscriptions
has_many :subscribers, :through => :subscriptions, :source => :user
end
您正在将用户关联重命名为订阅者。如果您不提供:源,Rails将在Subscription类中查找名为subscriber的关联。您必须告诉它使用Subscription类中的用户关联来生成订阅者列表。
有时,您希望为不同的关联使用不同的名称。如果您希望用于模型上的关联的名称与: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
在本例中,我们选择命名空间Dog::Breed,因为我们想访问Dog.find(123)。作为一种美好而方便的联想。
现在,如果我们现在想在Pet上创建一个has_many:dog_breed,:through =>:dogs关联,我们突然遇到了一个问题。Rails将无法在Dog上找到一个:dog_breed关联,因此Rails不可能知道您想使用哪个Dog关联。输入:来源:
class Pet < ActiveRecord::Base
has_many :dogs
has_many :dog_breeds, :through => :dogs, :source => :breeds
end
使用:source,我们告诉Rails在Dog模型上寻找一个名为:breed的关联(因为该模型用于:dogs),并使用它。