简体   繁体   中英

Ruby on Rails has_many :through Associations. Would this work?

I have a model Shop and a model Customer. A shop can have many customers and a Customer can buy stuff from many shops. for this relationship I've created a join model ShopCustomers.

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

Models

 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

Shop owners want to be able to group customers and therefore I added another model CustomersGroups.

class CustomersGroup < ActiveRecord::Base
  belongs_to :shop
end

And the Customers are added to a group through another join model.

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

Is this the correct way of doing such kind of a relationship or this is a recipe for doom and am I missing something that would make this not to work.

No, this is not the usual way of doing it. Have a look at the "has and belongs to many" association (AKA: HABTM). It will create the shops_customers join table for you and maintain it without you having to do it by hand.

here's a link to the apidock on HABTM: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM