0

我正在尝试了解 Rails 关联

我有以下表格,我必须定义它们的关系,任何人都可以帮助我理解。这些表是 Products、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

这个对吗?如果不是,我该如何纠正?

4

3 回答 3

0

我觉得问题出在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

于 2013-07-23T23:20:01.487 回答
0

如我所见,产品有一个(属于)分销商,而分销商有很多产品。所以你不需要使用 ProductDistributor

class Product < ActiveRecord::Base
   belongs_to :distributor
end

class Distributors < ActiveRecord::Base
   has_many :products
end

只需将列 *distributor_id* 添加到产品表中

我建议您阅读Active Record 关联指南以了解关联

于 2013-07-23T23:20:24.130 回答
0

使用的原因has_many through:是您需要使用未在标准 Rails 命名约定中命名的连接表。在这种情况下,ProductDistributor 有一个关联的表 (product_distributors),因为 Rails 约定按字典顺序将表放在名称中并将它们复数。Rails 表名称为distributors_products. distributors如果您创建了这样一个表,其中的 id和表的 id 具有外键,则products无需指定连接表,您只需has_and_belongs_to_many :distributors在 Products 和has_and_belongs_to_many :productsDistributors 上说。

坦率地说,你所拥有的并不完全适合你想要完成的事情。您在产品和分销商之间存在多对多关系。如果您真的想要 Product 和 Distributor 之间的 many_to_one 关系,您应该进行以下更改:

架构更改:删除 product_distributors 表并将产品的外键添加到分销商。

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

模型更改:删除 ProductDistributor 的模型,将 Product 和 Distributor 更改为直接相互引用。另请注意,Distributors 已重命名为 Distributor。

class Product < ActiveRecord::Base
   belongs_to  :distributor
end

class Distributor < ActiveRecord::Base
   has_many :products
end
于 2013-07-23T23:22:26.673 回答