簡體   English   中英

Ruby on Rails Model / 數據庫關聯

[英]Ruby on Rails Model / Database Associations

我有一個用戶 model、農民 model、醫生 model 和教育 Z20F35E6305394DBFA4C8C3F6

一個農民有一個用戶和許多教育。

醫生有一個用戶和許多教育。

如何為教育 model 設置數據庫?

它應該有一個farmer_id 和一個doctor_id 嗎?

但是教育不能同時屬於農民和醫生。 這是一個或另一個。

所以我的教育數據庫條目要么填寫一個farmer_id 要么填寫一個醫生ID,但不能同時填寫。

有沒有辦法保證一次只能填寫一個id?

或者有沒有更好的方法來關聯這些模型?

您的幫助將不勝感激!

哦,不用擔心模型的名稱(農民、醫生等)。 這只是一個例子。

我認為根據角色以這種方式建立關系是合適的。

Class User
  has_one :role
  has_many :educations
end

Class Role
  #What ever roles you have.
  #Farmer or Doctor
  belongs_to :user
end


class Education
  belongs_to :user
end

這樣您就可以將 user_id 存儲在教育 object 中,從而解決您的問題。

對於這種情況,我看到了兩種可能的解決方案。

第一個是利用多態關聯進行教育。 這可能看起來像這樣:

class Farmer < ActiveRecord::Base
  belongs_to :user
  has_many :educations, :as => :profession
end

class Doctor < ActiveRecord::Base
  belongs_to :user
  has_many :educations, :as => :profession
end

class Education < ActiveRecord::Base
  belongs_to :profession, :polymorphic => true
end

因此,教育不是具有醫生 ID 或農民 ID,而是具有一個職業 ID 和一個職業類型。

第二種解決方案是使用單表 Inheritance。 在您的場景中,這可以通過讓醫生成為用戶而不是屬於用戶來實現。 當然,對於農民來說也是如此。 這可能看起來像這樣:

class User < ActiveRecord::Base
  has_many :educations
end

class Farmer < User
end

class Doctor < User
end

class Education < ActiveRecord::Base
  belongs_to :user
end

在這種情況下,您將向用戶 model 添加一個類型列來存儲它是什么類型的 class 然后在教育 model 中只有一個 user_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM