【问题标题】:Rails Model Complex AssociationsRails 模型复杂关联
【发布时间】:2014-04-14 21:12:30
【问题描述】:

我有一个用户模型和一个名为邀请模型的用户之间的直通表。

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

我的迁移文件如下所示:

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

我不确定如何构建具有适当关联的用户模型。我希望一个用户属于一个邀请者并且有很多邀请。我应该如何适当地更新我的用户模型。

【问题讨论】:

    标签: ruby-on-rails model associations


    【解决方案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
    

    【讨论】:

    • 来自this website about indexes:“连接操作将数据从规范化模型转换为适合特定处理目的的非规范化形式。连接对磁盘查找延迟特别敏感,因为它结合了分散的数据片段。正确索引再次成为缩短响应时间的最佳解决方案。”在这种情况下,您将经常通过invites 表加入。
    猜你喜欢
    • 1970-01-01
    • 2017-01-31
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多