2014-04-14 208 views
0

我有一個用戶模型和一個通過用戶被稱爲邀請模型之間的表。Rails模型複雜關聯

我希望用戶能夠邀請他人,被邀請並創建關聯。

我的遷移文件看起來像這樣:

class CreateInvites < ActiveRecord::Migration 
    def change 
    create_table :invites do |t| 
     t.integer :invited_id 
     t.integer :inviter_id 
     t.timestamps 
    end 
end 

在我的邀請型號我有以下幾點:

class Invite < ActiveRecord::Base 
    belongs_to :invited, :class_name => 'User' 
    belongs_to :inviter, :class_name => 'User' 
end 

我不能確定如何構建與適當的關聯用戶模型。我想要一個用戶屬於一個邀請人,並有許多邀請。我應該如何適當地更新我的用戶模型。

回答

1
class User < ActiveRecord::Base 
    has_many :sent_invites, :class_name => "Invite", :foreign_key => :inviter_id 
    has_many :inviteds, :through => :sent_invites 

    has_one :invite, :foreign_key => :invited_id 
    has_one :inviter, :through => :invite 
end 

邊欄,一般是添加索引外鍵,像這樣一個好主意:

class CreateInvites < ActiveRecord::Migration 
    def change 
    create_table :invites do |t| 
     t.references :invited 
     t.references :inviter 
     t.index :invited_id 
     t.index :inviter_id 
     t.timestamps 
    end 
    end 
end 
+0

爲什麼是一個好主意,添加索引?謝謝 – stecd

+0

從[這個關於索引的網站](http://use-the-index-luke.com/sql/join):「連接操作將數據從規範化模型轉換爲適合特定處理目的的非規範化形式。連接對磁盤搜索延遲特別敏感,因爲它將分散的數據碎片合併在一起,適當的索引也是減少響應時間的最佳解決方案。在這種情況下,你會經常通過'invites'表加入。 – Ben