2011-04-20 3 views
1

mongoid 및 Rails로 역 정규화를 수행하는 가장 좋은 방법은 무엇입니까?mongoid로 역 정규화

"임베디드"관계를 사용하는 것은 작동하지 않습니다 (또는 원래의 전체 문서를 포함하는 것 이외의 용도로 사용하지 마십시오).

내 현재의 솔루션을 저장하고 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 

편집 : 나는 그것은 예에서합니다 (비정규 특성을 평평 https://github.com/logandk/mongoid_denormalize

시도했다는 것을 언급해야한다 ({name : "First Co-Author", _id : 1}, {name : "name"}, {name : "value"} 대신 author_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 

올바른 해결책에는 new_record와 같은 ActiveModel 메서드가 있습니까? * _path 및 * _url 라우팅 도우미와 함께 작동합니다.

+1

예제를 추가하여 비정규화할 수 있습니까? – Voldy

+0

예 : – Jason

+0

을 제공하는 편집 된 원본 게시물 MongoDB in Action (p62)에서 가져온 또 다른 예는 전자 상거래 주문입니다. 배송 주소와 품목/가격을 비정규 화합니다. 몽고이드에서 어떻게 완성 될까요? – Raphael

답변

-1

사용자가 책에 포함 된 작성자 문서로 저장됩니다.

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 
+0

사용자의 이름이 북 문서로 비정규 화되는 곳을보고 싶지 않습니다. – Jason

+0

이것은 비정규 화가 아닙니다. – Raphael