如何在轨道上的红宝石中创建User,Patient和Doctor表之间的关系?

时间:2015-03-16 06:41:42

标签: ruby-on-rails ruby sqlite

我有三张桌子:

  • 一个用于存储用户登录信息的用户 其列为nameemailpasswordroleidrole是告诉他是doctor还是patient还是admin

  • 下表是Patient表,仅存储id以及患者的其他信息,nameemailid以及password除外。要创建关系,此表的id取决于id User表,以获取nameemail

  • 我的最后一张表是Doctor表,它还存储了id和其他医生信息。此处id也取决于Userid列。

我的问题是如何在ruby on rails上创建这种关系?

我只是在铁轨上使用红宝石的首发 我正在使用sqlite db

1 个答案:

答案 0 :(得分:1)

如果您的系统中单个用户可以同时拥有多个角色,则可以使用@Santhosh提供的解决方案,如果它不能同时具有不同的角色(即Patient不能是具有相同用户帐户的Doctor,您应该按如下方式设计模型:

# User model
class User < ActiveRecord::Base
    # This is a polymorphic association, it means that a User instance
    # Can belong another instance from different models, in this case
    # a 'Doctor', a 'Patient' or an 'Admin' instance.
    # How this works? this instructs ActiveRecord to check the type of 
    # the associated instance in the column `profile_type` to get
    # in which model the associated record can be found.
    belongs_to :profile, polymorphic: true

    def role
       profile.profile_type.downcase # 'admin', 'doctor' or 'patient'
    end
end
# Migration
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string  :name
      # This will add two columns 'profile_id' 'profile_type'
      t.references :profile, polymorphic: true, index: true

      t.timestamps null: false
    end
  end
end

# Patient model
class Patient < ActiveRecord::Base
    # lets just keep it user, rather than complicating it by naming account
    has_one user, as: :profile
end
# Migration
class CreatePatients < ActiveRecord::Migration
  def change
    create_table :patients do |t|
      # add here the attributes of the patient

      t.timestamps null: false
    end
  end
end

# Doctor model
class Doctor < ActiveRecord::Base
    has_one user, as: :profile
end
#Migration
class CreateDoctors < ActiveRecord::Migration
  def change
    create_table :doctors do |t|
      # add here the attributes of the doctor

      t.timestamps null: false
    end
  end
end

# Admin model
class Doctor < ActiveRecord::Base
    has_one user, as: :profile
end
#Migration
class CreateAdmins < ActiveRecord::Migration
  def change
    create_table :admins do |t|
      # add here the attributes of the admin

      t.timestamps null: false
    end
  end
end

就像这样一个用户只能拥有一个个人资料。

对于病人来说

@user = User.create(name: 'Patientx', email: 'patientx@example.com')
@user.profile = Patient.create(patient_attributes)
@patient = @user.profile
@patient.user # returns @user

对于医生

@user = User.create(name: 'DoctorY', email: 'doctory@example.com')
@user.profile = Doctor.create(doctor_attributes)
@doctor = @user.profile
@dotcor.user # returns @user

对于管理员

@user = User.create(name: 'AdminZ', email: 'adminz@example.com')
@user.profile = Doctor.create(admin_attributes)
@admin = @user.profile
@admin.user # returns @user