【问题标题】:Ruby on Rails has_many :through Associations. Would this work?Ruby on Rails has_many:通过关联。这行得通吗?
【发布时间】:2012-01-14 04:05:45
【问题描述】:

我有一个模型 Shop 和一个模型 Customer。一家商店可以有很多顾客和一个顾客 可以从很多商店买东西。对于这种关系,我创建了一个连接模型 ShopCustomers。

create_table :shop_customers do |t|
  t.integer :shop_id
  t.integer :customer_id
  t.timestamps
end

型号

 class Shop < ActiveRecord::Base
   has_many :shop_customers, :dependent => true
   has_many :customers, :through => shop_customers
   has_many :customers_groups
 end

class Customer < ActiveRecord::Base
   has_many :shop_customers, :dependent => true
   has_many :shops, :through => shop_customers
   belongs_to :customers_group_membership
end

class ShopCustomer < ActiveRecord::Base
   belongs_to :shop
   belongs_to :customer
end

店主希望能够对客户进行分组,因此我添加了另一个 为客户组建模。

class CustomersGroup < ActiveRecord::Base
  belongs_to :shop
end

客户通过另一个加入模型添加到一个组中。

create_table :customers_group_memberships do |t|
  t.integer :customers_group_id
  t.integer :customer_id
end

class CustomersGroupMembership < ActiveRecord::Base
  has_many :customers
  belongs_to :customers_group
end

这是建立这种关系的正确方式吗?或者这是一个秘诀 对于厄运,我是否错过了一些会使这不起作用的东西。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 database-design activerecord entity-relationship


    【解决方案1】:

    不,这不是通常的做法。看看“拥有并属于许多”协会(AKA:HABTM)。它将为您创建并维护 shop_customers 连接表,而无需您手动操作。

    这里是 HABTM 上 apidock 的链接:http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

    【讨论】:

    • 我没有使用 habtm,因为我在我的连接模型中添加了其他字段。 Josh Susser 对这两种方法以及每种方法的优缺点进行了巧妙的比较here。我实际上要问的是,我不确定我的直通关联是否有缺陷。
    • 好的,那不是问题。我回答了您实际提出的问题,而不是您的意图;) 做您实际要求的最佳方法是让 rails 为您完成。
    • 如果您不希望这些东西实际上是连接表模型 - 那么我建议将它们命名为真实模型,例如“Membership”或“CustomerRelationship”......而不是 ShopCustomer - 有意义的名称对真实模型有感觉。
    • 回答你想问的问题 - 是的,这样就可以了。
    • 感谢 Taryn,CustomerRelationship 是一个更好的模型名称。并感谢您的代码气味测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2010-12-28
    • 2011-01-13
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多