☆ Required table ・ Users table ・ Relationships table (intermediate table) ☆ Point ・ The association is different from the usual "many-to-many"
Execute relationships, which are intermediate tables, using associations to create a "many-to-many" relationship between user tables. Because followers are also users. First, let's create a relationships model.
Terminal
$ rails g model Relationship follower_id:integer followed_id:integer
The columns of the relationships table
column | type |
---|---|
follower_id | integer |
followed_id | integer |
Will be.
Please edit as below
db/migrate/_creation_relationships.rb
class CreateRelationships < ActiveRecord::Migration[5.2]
def change
create_table :relationships do |t|
t.integer :follower_id
t.integer :followed_id
t.timestamps
end
add_index :relationships, :follower_id
add_index :relationships, :followed_id
add_index :relationships, [:follower_id, :followed_id], unique: true
#add_index :table name,Column name
end
end
By using add_index, data can be read / acquired faster. Once this is done, reset the migration file and use seed to populate the database with the initial data.
Terminal
$ rails db:migrate:reset db:seed
First of all Write the association in the relationships model.
models/user.rb
#Take out the people you follow
has_many :active_relationships, foreign_key: "follower_id",
class_name: "Relationship",
dependent: :destroy
class_name: You can specify the Relationship class directly by using "Relationship"
models/relationship.rb
class Relationship < ApplicationRecord
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed__id, presence: true
end
** class_name: By supplementary setting with'User' **, it is prevented to refer to the non-existing class called follower/followed class, and it is clearly stated that it is a User class. In short, it means "belongs_to to the user model because there is no follower/followed model!".
models/user.rb
has_many :active_relationships, foreign_key: "follower_id",
class_name: "Relationship",
dependent: :destroy
#
has_many :followed_users, through: :active_relationships, source: :followed
Recommended Posts