1

I have a list of items in a table and I'd like to create collections of those items in a new table. I've looked at has_many and has_many :through but I'm not sure those are the right choice and I'm not entirely sure how they'd work in my situation.

One special circumstance is that I want the items from the table to be identified by a unique field called typeID instead of the normal ID.

More information:

My model:

  create_table "products", :force => true do |t|
    t.integer  "typeID"
    t.string   "name"
    t.decimal  "basePrice",   :precision => 17, :scale => 4
    t.datetime "created_at",                                 :null => false
    t.datetime "updated_at",                                 :null => false
  end

I have a bunch of products and I need to have some of them bundled into packages (to sell as a bundle) that I can work with. The products will need to be able to be included in multiple different bundles.

4

2 回答 2

3

在最简单的情况下,您只需要一个one to manymany to many关系

一对多:假设一个包可以包含多个项目

class Package < ActiveRecord::Base
    has_many :products
end


class Product < ActiveRecord::Base
    belogs_to :package
end

通过这种方式,您可以将您的捆绑products在一个包中。

多对多(可能您需要这个)基于您问题的最后更新。

class Package < ActiveRecord::Base
    has_and_belongs_to_many :products
end


class Product < ActiveRecord::Base
    has_and_belongs_to_many :packages
end

现在,您的包裹还应该有一个价格列,其中包括所属产品的价格(可能有一些折扣:)。这有帮助吗?


您可能不需要这个:
但是,如果您的产品分为多种类型(食品、电子产品、服装等),并且您希望为每种类型的继承创建单独的模型,Product那么您只需要拥有一个Single Table Inheritance.


于 2012-08-27T10:07:29.273 回答
1

如果每个产品只属于一个包,我会推荐与 Samiron's 类似的方法。

但是,如果不是这种情况,我会推荐 has_many :through 。这是一个例子:

class Package
  has_many :product_listings
  has_many :products, :through => :product_listings

  # allows you to make convenient create/build calls like i do below
  accepts_nested_attributes_for :product_listings
end

class Product
  # defining these relations are only necessary if you want to be able to get all
  # packages a product exists in
  has_many :product_listings
  has_many :packages, :through => :product_listings
end

class ProductListing
  belongs_to :package
  belongs_to :product

  attr_accessible :package_id, :product_id
end

然后,在某些方面,您可以执行以下操作:

Package.all.each do |package|
  <%= package.name %>  # or whatever attribute the package has
  package.products.each do |product|
    <%= product.name %>  # or whatever attribute the product has
  end
end

编辑

请参阅对 Package 模型的补充。

将产品添加到包中的方法如下:

package = Package.create(:name => 'some package')

# Rails naming convention for attributes is snake_case, not camelCase (if you care) 
product = Product.create(:name => 'mouse', :base_price => 20.00)

package.product_listings.create(:product_id => product.id)
于 2012-08-27T10:17:32.243 回答