【发布时间】:2015-07-30 06:37:55
【问题描述】:
我正在尝试在User 和User 之间建立多对多关系,其中用户有很多关注者,也有很多关注者。
我通过一个名为 Follow 的模型创建了一个数据透视表,这是迁移文件:
class CreateFollows < ActiveRecord::Migration
def change
create_table :follows do |t|
t.integer :follower_id, index: true
t.integer :followed_id, index: true
t.timestamps null: false
end
add_index :follows, [ :follower_id, :followed_id ], unique: true
end
end
但是,我无法定义 has_many。我试过这样做:
user.rb:
has_many :followers, foreign_key: "followed_id", class_name: "Follow"
has_many :followed, foreign_key: "follower_id", class_name: "Follow"
follow.rb:
class Follow < ActiveRecord::Base
belongs_to :followed, class_name: "User"
belongs_to :follower, class_name: "User"
end
但是,当尝试像 @user.followers << @user_to_be_followed 这样尝试将用户添加到关注者或关注的集合时,我收到一个类型错误,提示应该是 Follow,而不是 User。有道理。
但是我如何定义has_many 说模型应该是User 但外键按定义调用并且表是follows?
我怎样才能做到这一点?
编辑搜索我偶然发现this 看起来我这样做的方式是正确的......
【问题讨论】:
-
你考虑过使用acts_as_follower
-
我不知道那个。但是要知道,我已经付出了我想以我正在尝试的方式去做的努力。尤其是当它看起来我做得对时
标签: ruby-on-rails ruby-on-rails-4