Rails 5.
I have been trying to create a self referencing has_many relationship based on this tutorial: https://medium.com/@jbmilgrom/active-record-many-to-many-self-join-table-e0992c27c1e (the last piece: Has_many | Has_many — Self Join Table)
I also see various threads here about this concept but I'm still a little lost when it comes to my problem and its terminology. And I am not sure what the database should look like. I should also mention that I am very new to Rails.
I am trying to create 'representative' - 'represented' relationship between Users.
A User can be represented by many Users (User has_many Representatives). And a User can represent many Users (User has_many Represented).
Based on the tutorial in the link above I wrote my User model like this:
class User < ApplicationRecord
has_many :representatives, through: :representive_link, source: :representative
has_many :representive_link, foreign_key: :represented_user_id, class_name: 'representatives'
has_many :represented, through: :represented_link, source: :represented
has_many :represented_link, foreign_key: :representative_user_id, class_name: 'representatives'
end
Then I created a representatives table like so (I called it representatives but its really the group of representatives and represented):
class Representatives < ActiveRecord::Base
belongs_to :representative, foreign_key: 'representative_user_id', class_name: 'User'
belongs_to :represented, foreign_key: 'represented_user_id', class_name: 'User'
end
I also created a representatives table in the database which looks like this:
+----------------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| representive_user_id | bigint(20) | YES | MUL | NULL | |
| represented_user_id | bigint(20) | YES | MUL | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+----------------------+------------+------+-----+---------+----------------+
So, In the Rails console I create two users:
u1 = User.create('id' => 1, 'username' => 'john')
u2 = User.create('id' => 2, 'username' => 'mike')
I want u2 to represent u1:
u1.representatives = [u2]
But I get this error:
NameError: uninitialized constant User::representatives
I'm finding this concept quite confusing and the other threads here don't clear it up for me. Can someone break this concept down in relation to my problem?