2011-03-10 50 views
6

我有一個表students與現場ward_id,我要創建一個帶有字段id,ward_idemailguardian_idhashed_password創建一個表,並添加外鍵約束

現在我必須添加一個名爲guardian_users表約束條件foreign key。學生的任何更新/刪除/編輯/插入應該對guardian_users具有相同的效果。

如何在rails 2.3.5中做到這一點?

表學生存在,但其他人不存在。

+0

沒有問題,但你仍然可以發表評論 – Kracekumar 2011-03-10 20:30:49

+0

「應該有相同的效果」 - 嘗試搜索級聯刪除。 – 2011-03-10 22:03:16

+0

@apneadiving:僅供參考,這是一個相當無用的評論。如果你有這種感覺,爲什麼要說什麼? – 2011-03-25 09:50:43

回答

6

您將需要foreign_key_migrations插件或#execute方法。假設你去插件:

class CreateGuardianUsersTable < ActiveRecord::Migration 
    def self.up 
    create_table(:guardian_users) do |table| 
     table.timestamps # I find them useful; YMMV 
     table.integer :guardian_id 
     table.integer :ward_id, :null => false, :references => [:students, :id] 
     table.string :email 
     table.string :heahead_password 
    end 
    end 

    def self.down 
    drop_table :guardian_users 
    end 
end 

而在你的機型:

class GuardianUser < ActiveRecord::Base 
    belongs_to :student 
end 

class Student < ActiveRecord::Base 
    has_many guardian_users:, :foreign_key => 'ward_id', :class_name => 'GuardianUser', :dependent => :destroy 
end 
+0

這就是我所發現的,對的,謝謝。 – Kracekumar 2011-03-26 03:59:29

-2

您將不得不首先生成您的遷移以構建guardian_users表。您可以閱讀來自Rails文檔的遷移並完成FK的遷移。您還需要將表示這兩個實體的任何模型與has_many或belongs_to之類的內容關聯起來。