2014-04-14 300 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