Rails模型复杂关联

时间:2014-04-14 21:12:30

标签: ruby-on-rails model associations

我有一个用户模型和一个名为Invite Model的用户名表。

我希望用户能够邀请其他人,被邀请并创建关联。

我的迁移文件如下所示:

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 个答案:

答案 0 :(得分: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