Ruby on rails访问另一个模型的模型信息

时间:2012-06-04 16:57:12

标签: ruby-on-rails ruby model mongoid

我的第一个模型Contact包含字段:email,我在模型:email中需要相同的字段Customer,其字段值为:email }在我的模型Contact中。

我使用mongoID进行ORM,所以这是我的第一个模型Contact

class Contact
  include Mongoid::Document
  include Mongoid::Timestamps
  embedded_in :customer
  embedded_in :employee
  embedded_in :restaurant

  field :city
  field :street
  field :zip_code
  field :country
  field :phone_number
  field :email

和我的第二个模特顾客

class Customer
  include Mongoid::Document
  include Mongoid::Timestamps
  embeds_one :contact

  devise :database_authenticatable, :lockable, :recoverable,
         :rememberable, :registerable, :trackable, :timeoutable, :validatable,
         :token_authenticatable

  attr_accessible :email, :password, :password_confirmation

  field :first_name
  field :last_name
  field :password
  field :gender
  field :encrypted_password

感谢。

2 个答案:

答案 0 :(得分:1)

如果您使用的是activesupport,那么代理人应该完成这项工作。

在customer.rb

delegate :email, :to => :contact

答案 1 :(得分:0)

你可以写自己的setter / getter

class Customer
  include Mongoid::Document

  embeds_one :contact

  def email
    contact.email
  end

  def email=(string)
    contact.update_attributes(:email => string)
  end
end