I am trying to set up a many to many relationship between User
and User
, where users have many followers and also follow many.
I created a pivot table via a model called Follow
, this is the migration file:
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
However, I can't get to define the has_many
. I tried doing this:
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
However when trying to add a user to the followers or followed collection like this @user.followers << @user_to_be_followed
I am getting an type error that saying Follow
is expected, not User
. Makes sense.
But how can I define has_many
saying that the model should be User
but the foreign keys are called as defined and the table is follows
?
How can I achieve this?
Edit searching around I stumbled on this an looks like the way I did it is correct...