ruby on rails - Has_and_belong_to_many relation with the same model -


i trying implement has_and_belong_to_many relation same model, don't know how.

for example, user should able follow other users.

also, have multiple fields of same model in model; how give name?

there 2 scenarios , 2 different implementations:


the 'friends' model

let's 1 user can have many :friends each friend object of user model. can way:

has_and_belongs_to_many :friends, class_name: 'user' 

this tells rails object of user class can have many-to-many relation friends. can call this:

@user_a.friends #=> [@user_x, @user_y, @user_z]  # array of user objects  @user_x.friends #=> [@user_a, @user_b, @user_c]  # array of user objects 

the 'followers/following' model

let's 1 user can follow other users have other users follow him. how you'll implement it:

has_many   :followers, class_name: 'user', inverse_of: :following belongs_to :following, class_name: 'user', inverse_of: :followers 

this tells rails each user can have many followers array of other user objects, , user accessible others object in following array. example, if @user2 follows @user1, this:

@user1.followers #=> [@user2, @user3]  @user2.following #=> [@user1] 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -