开发者

In many-to-many through a join table, is has_many / through optional?

开发者 https://www.devze.com 2023-02-15 17:25 出处:网络
I have 3 models: Customers, Stores, Signups (a mailing list) (Signups are their own object since they have state like opted in, opted out, blacklisted, etc)

I have 3 models: Customers, Stores, Signups (a mailing list)

(Signups are their own object since they have state like opted in, opted out, blacklisted, etc)

Customers and Stores are fairly independent and currently have no direct association to each other.

However, we're adding a 'mailing list' construct, Signups:

Signup belongs_to :store AND :customer
Store has_many :signups 
Customer has_many :signups

It's not clear to me under what conditions I would need to include:

store has_many :customers, :through => :signups
customer has_many :stores, :through => :signups

Without the :through when a store X sends a broadcast email to it's mailing list, we'd simply let mail_list = customers.signup.find( where store_id matches X)

Question 1:开发者_开发技巧 Is there any problem with that approach?

Question 2: if we DID add the :through, what would the query looks like to get all the customers who have a 'signup' for the current store?

Question 3: if we had 3 or 3 different joint tables between customers and stores (for example orders, invoices, signups, discountclubs) does that present any problem?


Question 1: Is there any problem with that approach?

The example you've given wouldn't work (the non :through approach) because if customers have many signups, customer.signup will only be available on a customer instance, not a collection. If you were to not use join tables, you'd have to either iterate over a lot of data to collect everything, or write some sql to deal with it, which means you're pretty much using a join table anyway, but inefficiently.

Question 2: if we DID add the :through, what would the query looks like to get all the customers who have a 'signup' for the current store?

store.customers would generate something along these lines:

SELECT `customers`.* FROM `customers` INNER JOIN `signups` ON `customers`.id = `signups`.customer_id WHERE ((`signups`.store_id = 1))

Question 3: if we had 3 or 3 different joint tables between customers and stores (for example orders, invoices, signups, discountclubs) does that present any problem?

No, it shouldn't be a problem. It's the right day to deal with those kind of relationships (well, maybe not orders and invoices unless they're common to multiple customers or something). Just make sure you put indexes on the right columns.

0

精彩评论

暂无评论...
验证码 换一张
取 消