[英]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 我有两个具有一对多关系的模型,我想从
relationships
模型中获取followers_id
并显示followers
信息
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) 我尝试在(rails console)中使用Rails的'pluck'方法
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) 但我不知道如何使用这些ID数组来获取
followers
信息(名字,姓氏)
Could someone please guide me.. 有人可以指导我..
Is there any better way to get followers info. 有没有更好的方法来获取关注者信息。
Thanks in advance :) 提前致谢 :)
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
之后,您可以只执行
user.followers
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_ids中获得所有关注者ID
@followers = User.where("id in (?)", @followers_id)
You get all information of followers inside @followers
variables 您可以在
@followers
变量中获取关注者的所有信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.