Hi I have an user model and I also have some fields for their information (name, email, bio, etc).
I want to be able to let an user add the products that they have to their account information.
It would only be the names of the products (text only), but I also want to be able to keep count of how many they have overall so I could show something like:
User has 10 products ( product 1, product 2, etc.)
I dont know exactly how go to about doing that. Thanks in advance.
The next step is: How does this allow a given product, e.g. unique UPC to be purchased by different users?
After all, a product such as ‘Large Lug Nut’ can be bought by various people.
So what you probably want is a purchases table which is a basically a join table and has the user_id and the product_id.
They you can do
user.purchases.countThis is usually done through a has_many :through relationship as in:
Strictly speaking it can also be done through a HABTM (has_and_belongs_to_many !) but this has largely fallen out of favor. It only allow for the two fields and it’s a virtual table that doesn’t exist in the database.
HABTM has mainly fallen out of favor because as soon as you want to add an additional attribute (very common in the real world) you need to switch to has_many, :through which can be a headache in a fully developed app.