【问题标题】:Mongoid associations & referencesMongoid 关联和参考
【发布时间】:2012-08-13 12:52:56
【问题描述】:

我有一个关于 Mongoid 关联的新手问题。我有这两个模型

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 应自动更改。

【问题讨论】:

    标签: ruby-on-rails associations mongoid


    【解决方案1】:

    当您已经在两者之间建立了关系时,为什么您需要在您的产品表中拥有一个制造商名称。

    做吧

    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)
    

    【讨论】:

    • 嗯,这似乎是我正在寻找的方式。我在 JSON API 后端编码,所以产品应该包含一个代表制造商的字段。我会玩那个......
    • 呵呵,又忘了一个细节:
    • m = Manufacturer.create 名称:“旧名称”,url:“www.foobar.com” p = m.products.create 型号:“Superduper”,价格:19.90 p.manufacturer.name返回我所期望的:“旧名称”然后我更改制造商的名称:foo = Manufacturer.first foo.name =“New name” foo.save! ...但 p.manufacturer.name 仍然返回“旧名称”。对此有任何提示吗?顺便说一句,MongoDB 只包含这个元素,所以 .first 引用了正确的文档。
    • 这是因为产品实例已经加载到内存中。如果您在控制台中更改了关联模型,则应该执行 p.reload.manufacturer.name。在正常的网络应用程序流程中,您在一个请求中更改制造商名称并在另一个请求中列出产品,所以这应该是一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多