1

テーブルにアイテムのリストがあり、それらのアイテムのコレクションを新しいテーブルに作成したいと思います。has_manyとhas_many:throughを見てきましたが、これらが正しい選択であるかどうかはわかりません。また、私の状況でそれらがどのように機能するかは完全にはわかりません。

特別な状況の1つは、テーブルのアイテムを、通常のIDではなくtypeIDと呼ばれる一意のフィールドで識別したい場合です。

詳しくは:

私のモデル:

  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

私はたくさんの製品を持っており、それらのいくつかを(バンドルとして販売するために)パッケージにバンドルして作業できるようにする必要があります。製品は、複数の異なるバンドルに含めることができる必要があります。

4

2 に答える 2

3

one to many非常に単純なケースでは、またはmany to many関係が必要です

1対多:パッケージに複数のアイテムを含めることができると想定

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と同様のアプローチをお勧めします。

ただし、そうでない場合は、代わりに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.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 に答える