1

I am lost in all the associations options Rails offers.

I have a table for Users. Those Users have Products. This is simply a has_many :products relationship.

However, I want to provide the users with a list of products. They will choose a number of products and will add a price to it.

So basically, I have

USER 1 ----->  PRODUCT 1 ------> PRICE 1    <----.
       ----->  PRODUCT 2 ------> PRICE 2         |
USER 2 ----->  PRODUCT 1 ------> PRICE 3    <----¨
       ----->  PRODUCT 3 ------> PRICE 4

Should I create three table : User, Product and Price?

And what if the user wants to customize his/her product more with a quantity, need, etc.? Then should I create the following tables instead :User, Product and ProductDetail

This way, a user has_many :product and a product has_many :product_detail.

What is the Rails way of doing this?

I am lost with all the has_many, has_one, has_many :through, etc.

4

1 回答 1

1

我将创建以下内容:

class User
  has_many :purchases
end

class Product
  has_many :purchases
end

class Purchase
  belongs_to :user
  belongs_to :product

  # mongoid syntax, if using ActiveRecord, use a migration
  field :quantity, type: Integer, default: 0
  field :price, type: Float, default: 0.0
end

user = User.new
apple = Product.new
tea = Product.new
chocolate = Product.new

user.purchases.build(product: apple, price: 2.99, quantity: 1)
user.purchases.build(product: tea, price: 5.99, quantity: 2)
user.purchases.build(product: chocolate, price: 3.99, quantity: 3)

仅供参考:和之间User的这种关系类似于 a 。使用, rails 时,只需像上面那样链接类。在这里,我们自己做,以便使用和自定义类。ProductPurchasehas_and_belongs_to_manyhas_and_belongs_to_manyPurchasequantityprice

于 2013-08-03T16:06:38.073 回答