在 rails 中访问链表属性模型
Accessing a linked list attribute model in rails
根据 previous question
如果我们使用 belongs_to 链接更多 table,如何在 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>
谢谢
将关联定义为:
class Article
#...
embeds_one :contact
#..
end
和
class Contact
#..
embedded_in :article
#...
end
然后,a.contact.email
。阅读 Embedded 1-1 了解更多信息。
根据 previous question 如果我们使用 belongs_to 链接更多 table,如何在 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>
谢谢
将关联定义为:
class Article
#...
embeds_one :contact
#..
end
和
class Contact
#..
embedded_in :article
#...
end
然后,a.contact.email
。阅读 Embedded 1-1 了解更多信息。