【问题标题】:Ruby on rails access to model information to an another modelRuby on rails 将模型信息访问到另一个模型
【发布时间】:2012-06-04 16:57:11
【问题描述】:

我有我的第一个模型Contact 和字段:email,我需要在我的模型Customer 中使用相同的字段:email 和字段:email 的值,它在我的模型Contact 中。

我将 mongoID 用于 ORM,所以这是我的第一个模型联系人

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

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby model mongoid


    【解决方案1】:

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

    在 customer.rb 中

    delegate :email, :to => :contact
    

    【讨论】:

      【解决方案2】:

      你可以写你自己的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
      

      【讨论】:

        猜你喜欢
        • 2010-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多