Exemplo de associação complexa de Rails

Olá, esta é minha primeira postagem, por favor, tenha paciência comigo.

Quando comecei a aprender trilhos, tive muitas dificuldades para entender e aprender associações. Mas eu não parei de tentar porque é tão assustadoramente incrível e tão cheio de magia (bem, foi o que eu pensei). Portanto, estou aqui para demonstrar uma associação complexa em que temos um modelo chamado Usuário e outro modelo chamado Relacionamento para simular um recurso de acompanhamento semelhante ao Twitter.

Eu sei que muitos de vocês já sabiam disso, mas eu gostaria de compartilhar meu próprio entendimento das associações de Rails. Para iniciantes, isso pode ajudar!

class User < ActiveRecord::Base

#let's just make it simple and only add one column for this model called 'username'
attr_accessible
:username

#use "follower_id" as the foreign key since by default it will use "user_id" which does
#not exist inside the "relationships" table
has_many
:relationships, foreign_key: :follower_id

#find all user with the ID matching the "followed_user_ids" of the result. If I did not
#include "source: :followed_user", it will look for the column "following_id" which is wrong
has_many
:followings, through: :relationships, source: :followed_user

#here we are just reversing the relationship. Instead of using "follower_id", we now use
#"followed_user_id"
has_many
:inverse_relationships, class_name:"Relationship", foreign_key: :followed_user_id

#this line will look for the "follower_id" based on the result of the "inverse_relationships".
#no "source" option is required since we have used the "followers" in the association thus
#it looks for a "follower_id" on the "relationships" table which it does
has_many
:followers, through: :inverse_relationships

end
class Relationship < ActiveRecord::Base

#Here, class_name just means that it's a User model.
belongs_to
:follower, class_name: "User"
belongs_to
:followed_user, class_name: "User"

end

Espero que isto ajude!