0

我在 Rails4 ans Mongoid 中使用具有单表继承的设计

Class User
  #devise class
  validates :email, :uniqueness => { :scope => :_type }
end

class Patient < User
end

class Doctor < User
end

class Hospital < User
end

如果我创建一个作为医生的帐户,_type: "Doctor"那么如果他想创建一个作为患者或医院的帐户,那么首先检查数据库,如果电子邮件已经存在任何帐户类型,然后只需使用该电子邮件创建一个具有以前凭据的帐户。

所以我不想在注册创建其他帐户类型时提供所有数据。

这个场景怎么实现!!!请帮我......

4

1 回答 1

0

如果我是你,我不会使用继承。我做这样的事情:

Class User
  field :name
  field :email
end

Class Patient
  has_one :user

  attr_accesor :email
  field: disease

  before_create do
    existing_user = User.where( email: email ).first

    if uxisting_user
      user = uxisting_user
    else
      # you need create first an user
    end
  end

  def name
    user.name
  end
end

现在如果用户已经存在,只需要搜索它的电子邮件字段,您就可以获得所有这些信息:

User.create( name: 'User1', email: 'user1@email.com' )
Patient.create( email: 'user1@email.com', disease: 'headache' )
Patient.first.name
=> "User1"

此外,如果您更改用户信息,它会在 Patient 中更改,对于其他类也是如此。

于 2014-01-13T13:39:30.607 回答