0

Mongoid のアソシエーションについて初心者向けの質問があります。私はこの2つのモデルを持っています

class Manufacturer
  include Mongoid::Document

  field :name, type: String
  field :url, type: String

  has_many :products
end

class Product
  include Mongoid::Document

  field :manufacturer_name, type :String
  field :model, type: String
  field :price, type: Float

  belongs_to :manufacturer
end

次に、新しい会社を作成します。

man = Manufacturer.create name: 'Flower Power Companies', url: 'www.flowerpower.com'

そして新製品:

prod = Product.create manufacturer_name: what_comes_here, model: 'Foo0815', price: '19.90'

prod.manufacturer_name を man.name に参照するには? man.name が変更される場合、prod.manufacturer_name は自動的に変更されます。

4

1 に答える 1

0

製品テーブルに cloumn Manufacture_name が必要な理由は、2 つの間に既に関係がある場合です。

やるだけ

m = Manufacture.create name: "...", url: "..."
p = m.products.create model: ".." , price : 19.90 

これにより、製造元と製品の間の関係が自動的に作成されます。後で製造元の名前を知りたい場合は、単に p.manufacture.name を呼び出します。

新しい製品を作成し、後で製品に製造を追加したい場合は、次のようにします。

p = Product.create model: "",price: ""
p.manufacture = Manufacture.find(:id)
于 2012-08-13T12:58:58.963 に答える