带有关注/取消关注按钮的用户列表 [英] Users list with follow/unfollow button
问题描述
我有一个用户列表
,我需要在登录时为每个用户放置follow/unfollow
按钮.
I have an Users list
, where I need to put follow/unfollow
button for each user when I'm signed in.
我想在其他一些地方使用相同的方法来关注主题/组等.所以我认为最好编写一个关联以避免每次我需要这些按钮时的额外查询.
There will be some other places where I want to use same method to follow topic/group and etc. So I think it would be best to write an association to avoid additional queries every time I need these buttons.
我的user_followings
表结构
| id | user_id | recipient_id |
| 1 | 1 | 2 |
| 2 | 3 | 2 |
| 3 | 10 | 3 |
所以这里 id=1 的用户跟随用户 => 2...
So here user with id=1 follows user => 2...
所以基本上有 has_many
关联类型,因为用户正在关注许多其他用户.但是我想出了一个添加 has_one
关联类型的想法,我将在其中添加一个附加条件 recipient_id=current_user.id
所以只剩下一条记录,它显示如下地位.
So bassicaly there is has_many
association type, because user is following many other users. But I came up with an idea to add has_one
association type, where I will put an additional condition recipient_id=current_user.id
so only one record will be left and it shows following status.
如果我成功建立了这个association
,将非常容易通过user.following.nil?
查看以下状态,无需额外的查询、缓存等.
If I succeed making this association
, there will be super easy to check following status via user.following.nil?
in view with no additional queries, caching and etc.
我之前在我的 CakePHP 应用程序中做过一次,SQL 查询如下所示:
I have made this once before in my CakePHP app, the SQL query looks like:
ON (`UserFollowing`.`recipient_id` = `User`.`id` AND `UserFollowing`.`user_id` = 1)
但是 CakePHP 允许动态绑定关系,因此我将会话中的 current_user.id 直接添加到关联条件.
But CakePHP lets to bind relations on the fly, so I added current_user.id from the session directly to association conditions.
我不能在 Rails 中这样做,因为我不能将 current_user.id
放在模型中来描述条件:
I can't do this in Rails, because I can't put current_user.id
in model to describe conditions:
user.rb
has_one :following, :class_name => 'UserFollowing', :conditions => {:user_id => current_user.id}
方法 Nb.2
也许我可以使用 :through
解决这个问题,但是我找不到任何示例来从我进行关联的同一个 users
表中获取结果.
Maybe I can solve this using :through
, but I can't find any example to get results from the same users
table from which I'm making the association.
方法 Nb.3
使用范围 Rails 3 设计, current_user 在模型中不可访问?
不确定,哪种方式最好...
Not sure, which way is the best...
推荐答案
虽然它不是您问题的直接答案:请考虑一下 gem:acts_as_follower.我将它用于类似的情况,它似乎符合您的需求.可以让任何事情跟随其他任何事情 - 检查一下...
although it's not a direct answer to your question: consider the gem: acts_as_follower. I used it for a similar situation and it seems to fit your needs. It's possible to let anything follow anything else - check it out...
这篇关于带有关注/取消关注按钮的用户列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!