Looking for some guidance on the best way to implement this scenario:
I have an items table (of products) and want to support the ability to cross-sell / up-sell / complement items. So there is an item-to-item(s) relationship here. In this join table I need to include additional attributes beyond the keys such as the sales_relation between the items (e.g., cross, up, complement, substitute, etc).
How do I go about setting up the Model associations?
By the sounds of it, this join table represents a whole new model. I’m not sure exactly what your requirements are, but I’ll play out one potential solution. For now, let’s call the join model a SalesRelationship.
I’m going to call the item/product objects “products”, since to me it’s a little less generic.
The migration for this would look something like:
You can include any other attributes necessary in that migration as well. Next, create a SalesRelationship model:
Then, create subclasses for the different types of relationship:
Then set up the relationships on the Product model:
Now you should be able to create and add related products all you want.
For extra credit, you could write a simple validation on the SalesRelationship model that ensures a product is never related to itself. That may or may not be necessary, depending on your requirements.