I have a User model and a Product model with a many-to-many association and in both models I have "has_and_belongs_to_many"
I understand that this allows me to work with relations like this:
user = User.first
user.products #shows all products bought by a user
and
product = Product.first
product.users # show all users who bought that product
But there might be a product which has not been bought by any user yet, so this product will be in products table but not in the user_products join-table.
How do I return only user-products associations which have been saved in the join table?
Also, say I want to create a product and at the same time define that it has been bought by - belongs to - first and second user. I thought of:
User.all[0..1].each {|usr| usr.product.create(name: "tv")}
Is this the correct way to imply an association and populate the join-table with a record for it?
What if, as I said above, I have a product that is in products table but still no User had bought it, and now a user buys it: how can I express this so that later I can do
user.products
and see that product?