ankit
ankit

Reputation: 125

Need to display list of followers information

I am a ruby on rails beginner.

I have two models with one-to-many relationships and i want to get followers_id from relationships model and display the followers information

model1 

Users  -> has_many                      
id firstname lastname....
 1    sample   

model2

Relationships -> belongs_to              
user_id follower_id following_id
 1         2         
 1         3     

I have tried using 'pluck' method of rails in (rails console)

u  = Users.find(1)

r  = u.relationships.pluck(:follower_id)
//gives me a array of id

But I don't know how to use these arrays of ids to get followers info(firstname,lastname)

Could someone please guide me..

Is there any better way to get followers info.

Thanks in advance :)

Upvotes: 0

Views: 294

Answers (2)

simanchala
simanchala

Reputation: 127

Based on Your Model relationship

@user  = Users.find(1)

@follower_ids  = @user.relationships.pluck(:follower_id)

You get all the follower ids in @followers_ids

@followers = User.where("id in (?)", @followers_id)

You get all information of followers inside @followers variables

Upvotes: 0

Edgars Jekabsons
Edgars Jekabsons

Reputation: 2853

Ok, what You basically need is to connect Users with Followers through Relationships this is done like this:

class User < ActiveRecord::Base
  has_many :relationships
  has_many :followers, through: :relationships
end

class Relationship < ActiveRecord::Base
  belongs_to :user
  belongs_to :follower
end

After that You can just do user.followers

Upvotes: 1

Related Questions