首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mongoid进行反规范化

使用mongoid进行反规范化
EN

Stack Overflow用户
提问于 2011-04-21 03:28:22
回答 1查看 991关注 0票数 1

用mongoid和Rails去规范化的最好方法是什么?

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

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

代码语言:javascript
复制
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

编辑:我应该提一下,我确实尝试过https://github.com/logandk/mongoid_denormalize

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

编辑:请求了一个示例。

代码语言:javascript
复制
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

正确的解决方案应该是使用new_record这样的ActiveModel方法。与*_path和*_url路由助手一样工作。

EN

回答 1

Stack Overflow用户

发布于 2011-04-21 04:44:03

这会将用户存储为书中嵌入的author文档。

代码语言:javascript
复制
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
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5735610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档