2014-01-27 154 views
2

我有以下型號軌道4 MongoID嵌入文檔

class Professional 
    include Mongoid::Document 
    field :first_name, type: String 
    field :last_name, type: String 
    field :company_name, type: String 
    field :address, type: String 


    validates :first_name, length: { minimum: 5, :message => "What" }, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } 
end 

我想包括一個嵌入文檔在那裏我可以存儲多個辦公地址。在尋找的DB

{ 
    "first_name": "Harsha", 
    "last_name": "MV", 
    "company_name": "Mink7", 
    "offices": [ 
    { 
     "name": "Head Office", 
     "address": "some address here" 
    }, 
    { 
     "name": "Off Site Office", 
     "address": "some large address here" 
    } 
    ] 
} 

回答

5

以下結構你必須定義該模型中嵌入Office對象,反之亦然,說明這裏:http://mongoid.org/en/mongoid/docs/relations.html。我猜你需要1-N關係,這樣專業人員才能嵌入多個辦公室?在這種情況下,應該這樣做。

專業模型

class Professional 
    include Mongoid::Document 
    field :first_name, type: String 
    field :last_name, type: String 
    field :company_name, type: String 
    field :address, type: String 


    validates :first_name, length: { minimum: 5, :message => "What" }, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } 

    embeds_many :offices, class_name: "Office" 
end 

辦模型

class Office 
    include Mongoid::Document 
    field :name, type: String 
    field :address, type: String 

    embedded_in :professional, :inverse_of => :offices 
end 

請記住,如果你要使用一種形式爲這些對象,你就必須做一個嵌套形式,類似的信息(或只是谷歌的東西了):

<%= form_for @professional, :url => { :action => "create" } do |p| %> 
    <%= o.text_field :first_name %> 
    <%= o.text_field :last_name %> 

    <%= o.fields_for :office do |builder| %> 
     <%= builder.text_field :name %> 
     <%= builder.text_field :address %> 
    <% end %> 
<% end %> 

注意:並沒有進行測試。

+0

非常感謝。如果我想添加多個辦公室,我可以添加兩組字段,它會保存嗎?我如何添加兩組字段? –

+1

很高興我能幫到你。我不確定這是否會起作用,也沒有時間來嘗試它。但是,您可以只做那個試驗和錯誤,無論如何,您已經有了代碼。=) – oskarno

+0

也許您也可以共享您的控制器,這應該有辦公室空,從而不顯示辦公室的名稱和地址。 – Dennis