簡體   English   中英

如何在Rails中指定帶有2個外鍵的表?

[英]How do I specify a table with 2 foreign keys in rails?

如果我有一個舊數據庫,則在另一個表中定義了兩個實體之間的關系。 如何在Rails中建立這種關系?

我要介紹的基本關系是:

---管理員:

First_name
Last_name
id

---網站:

id
subject

--- Admin_Sites

 id
 teacher_id
 class_id

我知道在Rails中我只會使用belongs_to:和has_many:但是,如果我有一個(不斷更新的)teacher_class表,我需要以某種方式指定那是Rails需要查找誰與哪個類相關的關系的地方。 我不知該如何指定。 是否可以在類模型中以某種方式將:foreign_key指定為“ teach_class.teacher_id”?

在教師模型中,您將擁有

has_many :teach_classes
has_many :classes, :through => :teach_classes

看到這個博客的has_many:通過關系- http://ruby-on-rails-dipak-panchal.blogspot.in/2012/10/has-many-through-relationship.html

class Admin < ActiveRecord::Base
  has_many :admin_sites
  has_many :sites, :through => :admin_sites
end

class Site < ActiveRecord::Base
  has_many :admin_sites
  has_many :admins, :through => :admin_sites
end

class AdminSites < ActiveRecord::Base
  belongs_to :admin
  belongs_to :site
end

暫無
暫無

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

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