Ruby on rails 表中具有外键的两个字段-Rails

Ruby on rails 表中具有外键的两个字段-Rails,ruby-on-rails,ruby,postgresql,ruby-on-rails-4,Ruby On Rails,Ruby,Postgresql,Ruby On Rails 4,我正在尝试使字段user\u id和下面的\u id具有user id字段的引用表。我什么都试过了,在互联网上搜索过,但还是不能 迁移: class CreateFollowers < ActiveRecord::Migration def change create_table :followers do |t| t.references :user, index: true, foreign_key: true t.references :f

我正在尝试使字段user\u id和下面的\u id具有user id字段的引用表。我什么都试过了,在互联网上搜索过,但还是不能

迁移:

    class CreateFollowers < ActiveRecord::Migration
  def change
    create_table :followers do |t|
      t.references :user, index: true, foreign_key: true
      t.references :following, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end
class CreateFollowers
型号:

class Follower < ActiveRecord::Base
  belongs_to :user, :class_name => 'User'
  belongs_to :following, :class_name => 'User'
end

class User < ActiveRecord::Base
  has_many :follower1_as_user, :class_name => 'Follower', :foreign_key => 'user_id'
  has_many :follower2_as_user, :class_name => 'Follower', :foreign_key => 'following_id'
end
class Follower“user”
属于:以下,:class\u name=>“用户”
结束
类用户'Follower',:foreign\u key=>'user\u id'
拥有多个:follower2\u作为用户,:class\u name=>'Follower',:foreign\u key=>'following\u id'
结束

我甚至阅读了文档,我总是看代码,我认为我是对的。

问题在于模型和表格的设计。您有一个用户(1)跟随另一个用户(2)。所以,1是跟随者,2是被跟随者

如果2也决定跟随1呢

您将有一个如下表:

关系

id/跟随者\ id/跟随者(或跟随者)\ id

1/1号/2号

2/2号/1号

你需要一个有许多可逆的关系。对于初学者来说,这是一个相当复杂的应用程序。幸运的是,这里有一本完美的图书指南,需要你花上几天的时间。看看


您所需要的就是这些。

如果表名与引用名不匹配,则
reference
方法不支持表的外键

一个解决方案是用更少的Rails魔法构建相同的系统:

def change
  create_table :followers do |t|
    t.references :user,         index: true, foreign_key: true
    t.integer    :following_id, index: true
    t.timestamps null: false
  end
  add_foreign_key :followers, :users, column: :following_id
end
此外,
Follower
模型中的关联声明也需要知道不明显的列名:

class Follower < ActiveRecord::Base
  belongs_to :user
  belongs_to :following, class_name: 'User', foreign_key: 'following_id'
end
class Follower
您能详细解释一下“拥有用户ID字段的参考表”吗?AFAICS用户参考的迁移是正确的。您的followind将假定有一个“following”表(因为您没有告诉它它要成为的类是用户)。另外:告诉我们为什么你知道它目前不起作用?你怎么知道的?