簡體   English   中英

請通過關聯說明rails has_many

[英]Please explain rails has_many through association

我正在嘗試了解Rails協會

我有下面的表格,我要定義它們之間的關系,任何一個都可以幫助我理解。 這些表是產品,ProductDistributors和Distributors。 每個產品都有一個分銷商,一個分銷商攜帶多個產品

我將這些定義為

class Product < ActiveRecord::Base
   has_one :product_distributor
   has_one  :distributor, through: :product_distributor
end
class ProductDistributor < ActiveRecord::Base
   belongs_to :products
   belongs_to :distributors   
end
class Distributor < ActiveRecord::Base
   has_many :product_distributors
   has_many :products, through: :product_distributors
end

這個對嗎? 如果沒有,我該如何糾正?

我覺得問題出在Distributors類名稱上,因為它是復數形式。 當您說has_many :distributors之類的內容時,默認情況下,Rails會鏈接到Distributor類,但是在您的情況下,該類名稱是Distributors

在您的關系聲明中添加class_name選項應該可以:

class Product < ActiveRecord::Base
   has_one :product_distributor
   has_one  :distributor, through: :product_distributor, class_name: 'Distributors'
end
class ProductDistributor < ActiveRecord::Base
   belongs_to :product
   belongs_to :distributor, class_name: 'Distributors' 
end
class Distributors < ActiveRecord::Base
   has_many :product_distributors
   has_many :products, through: :product_distributors
end

還要注意,您的belongs_to應該是單數而不是復數。 請查看協會指南以獲取詳細信息: http : //guides.rubyonrails.org/association_basics.html

如我所見,產品有一個(屬於)分銷商,而分銷商有許多產品。 因此,您無需使用ProductDistributor

class Product < ActiveRecord::Base
   belongs_to :distributor
end

class Distributors < ActiveRecord::Base
   has_many :products
end

只需在產品表中添加* distributor_id *列

我建議您閱讀Active Record Associations,以了解協會

使用has_many through:的原因是,您需要使用標准Rails命名約定中未命名的聯接表。 在這種情況下,ProductDistributor具有這樣一個關聯的表(product_distributors),因為Rails約定按字典順序將表放在名稱中並使其復數。 Rails表的名稱將為distributors_products 如果您使用外鍵指向distributorsproducts表的ID創建了這樣的表,則無需指定has_and_belongs_to_many :distributors表,您可以在Products上說has_and_belongs_to_many :distributorshas_and_belongs_to_many :distributors上說has_and_belongs_to_many :products

坦白說,您所擁有的並不完全適合您要完成的工作。 您與產品和分銷商之間存在多對多關系。 如果您確實希望產品與分銷商之間存在many_to_one關系,則應進行以下更改:

模式更改:刪除product_distributors表,然后將產品中的外鍵添加到分銷商。

drop_table :product_distributors
change_table :products do |t|
  t.references :distributors
end

模型更改:刪除ProductDistributor的模型,並更改Product和Distributor以直接相互引用。 另請注意,分發服務器已重命名為分發服務器。

class Product < ActiveRecord::Base
   belongs_to  :distributor
end

class Distributor < ActiveRecord::Base
   has_many :products
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM