在rails中访问链接列表属性模型

时间:2015-04-08 08:09:44

标签: ruby-on-rails attributes

根据previous question 如果我们使用belongs_to有更多链接表,如何在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>

由于

1 个答案:

答案 0 :(得分:0)

将关联定义为:

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

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

然后,做a.contact.email。请阅读Embedded 1-1以获取更多信息。