简体   繁体   中英

I want to let my users add their “products” and keep count of how many they have

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, eg 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.count

This is usually done through a has_many :through relationship as in:

User has_many :purchases
User has_many :products, :though => :purchases

Purchase belongs_to :user
Purchase belongs_to :product

Product has_many :purchases
Product has_many :users, :through => :purchases

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.

make a Product model with its own table.

then inside User do has_many :products

then you can do @user.products.count

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