Ruby on rails 用mongoid反规范化

Ruby on rails 用mongoid反规范化,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,使用mongoid和Rails反规范化的最佳方法是什么 使用“嵌入”关系似乎不起作用(或者只用于嵌入整个原始文档) 我当前的解决方案将非规范化属性作为OrderedHash存储和检索: collection.update({_id: id, ...}, {..., denormalized: {_id: other.id, _type: other._type, a: other.a, b: other.b}} def denormalized Mongoid::Factory.build

使用mongoid和Rails反规范化的最佳方法是什么

使用“嵌入”关系似乎不起作用(或者只用于嵌入整个原始文档)

我当前的解决方案将非规范化属性作为OrderedHash存储和检索:

collection.update({_id: id, ...}, {..., denormalized: {_id: other.id, _type: other._type, a: other.a, b: other.b}}

def denormalized
  Mongoid::Factory.build(attributes[:denormalized]["_type"], attributes[:denormalized])
end
编辑:我应该说我确实试过了

它平展了非规范化属性(在下面的示例中,它将存储author_name而不是author:{name:“value”},并且它不支持多个非规范化关系(例如,authors:[{name:“First Co-author”,_-id:1},{name:“Second Co-author”,_-id:2})

编辑:请求了一个示例

class User # this class uses STI so _type field is important
  include Mongoid::Document

  field :name # this is the field I want to de-normalize to where Users are referenced

   def write_book
     Book.create!({title: "Some Text", author: {_id: self.id, _type: self._type, name: self.name})
   end
end

class Book
  include Mongoid::Document

  field :title

  # embeds_one :author, polymorphic: true
  # tried this but it doesn't seem to be correct usage... it sort of works but
  # I run into problems with cycles and infinite loops when used extensively
  # because (I think) of how mongoid works internally, expecting embeds_one
  # to mean something different

  def author
    Mongoid::Factory.build(attributes[:author]["_type"], attributes[:author])
  end
end

正确的解决方案将使用ActiveModel方法,如new_record?以及*_路径和*_url路由帮助程序。

这将用户作为嵌入的作者文档存储在书中

class User
  include Mongoid::Document
end

#instead of the write book method, you could just do this:
book = Book.create(title: "Old Man And The Sea", users: [user])

class Book
  include Mongoid::Document

  embeds_many :authors

  field :title

  def users=(users)
    users.each do |user|
      authors.build(user: user, name: user.name)
    end
  end
end

class Author
  include Mongoid::Document

  embedded_in :book
  referenced_in :user

  field :name
end

你能添加一个例子吗?你想去规范化什么?编辑原始帖子以提供例子另一个例子(摘自MongoDB in Action,p62)将是一个电子商务订单。您将取消发货地址和商品/价格的规范化。在Mongoid中如何实现这一点?我不知道用户名称将在图书文档中的何处取消规范化。