用户有很多粉丝。
我的用户模型中有一个类似于
的方法def user_profile
ret = Hash.new
ret[:id] = id
ret[:name] = name
ret[:username] = username
ret[:bio] = bio
ret[:email] = email
ret
end
我想包括current_user是否跟随返回的用户。显然,“跟随”不是数据库中的字段,但我有一个存储用户及其关注对象的表。如何有效地向每个用户添加当前用户关注者是否包含他们?
也许在我的控制器中做地图或浏览每个用户结果?
答案 0 :(得分:0)
您需要在用户模型和以下方法之间创建一对多关联。在生成以下模型时,在添加以下方法的字段后添加User:belongs_to。
答案 1 :(得分:0)
我最终让它像这样工作,但我不认为这是最有效的方式。
基本上获取当前用户关注的所有人,并查看users数组中的用户是否与id匹配,并将true设置为true。
following = Follower.where(user_id: current_user.id)
users = users.map do |user_record|
user_record.as_json.tap do |user|
user[:following] = following.any? {|follower| follower.connection_id == user_record.id}
end