2015-04-08 28 views
0

根據previous question 如何在使用belongs_to的鏈接表更多的情況下在Rails中進行編碼。 對於以下:在rails中訪問鏈表屬性模型

class Article 
include Mongoid::Document 
include Mongoid::Timestamps 
field :name, :type => String 
field :content, :type => String 
field :published_on, :type => Date 
belongs_to :author 
embeds_many :comments 
validates_presence_of :name 
end 

class Author 
include Mongoid::Document 
include Mongoid::Timestamps 
field :name, :type => String 
belongs_to :contacts 
end 

class Contact 
include Mongoid::Document 
field :email, type: String 
field :phone, type: String 
field :line, type: String 
end 

然後,我怎麼能訪問電子郵件,如果我的控制檯看起來像這樣:

> a 
=> #<Article _id: 5509afbb4d42500909010000, created_at: nil, updated_at: 2015-03-19 09:55:41 UTC, name: "Pr", content: "My Content", published_on: nil, author_id: nil> 

> au 
=> #<Author _id: 551270b94d42500a09000000, created_at: 2015-03-25 08:24:25 UTC, updated_at: 2015-03-25 08:24:25 UTC, name: "Tim", address_id: nil, contacts_id: 1> 

> c 
=> #<Contact _id: 55237a7d4d425002df040000, email: "myemail.com", phone: "213 999999", line: "k.0"> 

我可以

> a.name 
=> "Pr" 

問題訪問名稱: 我怎樣才能訪問郵件?

> a.email 
NoMethodError: undefined method `email' for #<Article:0x007fed681d8280> 

感謝

+0

'@ user.contact.email' ...就夠了。注意:'用戶'表應該有'contact_id'列.. –

+0

我有「NoMethodError:undefined method' contact' –

+0

我將重寫我的問題,而不是從以前的問題擴展 –

回答

0

定義協會評爲:

class Article 
    #... 
    embeds_one :contact 
    #.. 
end 

class Contact 
    #.. 
    embedded_in :article 
    #... 
end 

然後,做a.contact.email。閱讀Embedded 1-1瞭解更多信息。

+0

如果嵌入它的工作,但聯繫是如何自己分離我應該叫a.contact.email? –

+0

@ T.Kul我沒有找到你,我剛剛創建了一個1對1的關聯,'Contact'仍然是一張單獨的表格 –

+0

我喜歡什麼以瞭解是否應該調用table1.table2.fieldIntable3 –