用户列出与后续/取消关注按钮(Users list with follow/unfollow but

2019-11-01 20:59发布

我有一个Users list ,在这里我需要把follow/unfollow按钮,每个用户在我参与的签名。

会有一些其他地方,我想用同样的方法来追踪主题/组等。因此,我认为这将是最好写的关联,以避免额外查询每次我需要这些按钮的时间。

user_followings表结构

| id | user_id | recipient_id | 
| 1  | 1       | 2            | 
| 2  | 3       | 2            | 
| 3  | 10      | 3            |

因此,这里使用id = 1用户按照用户=> 2 ...

所以bassicaly存在has_many关联类型,因为用户是继许多其他用户。 但是,我想出了一个主意,添加has_one关联类型,在那里我会放一个附加条件recipient_id=current_user.id所以只有一条记录会被留下,并显示以下状态。

如果我成功使这个association ,将有超级容易检查以下通过状态user.following.nil? 考虑到与没有附加查询,缓存和等

我在CakePHP的应用程序,一旦之前作出这样,SQL查询的样子:

ON (`UserFollowing`.`recipient_id` = `User`.`id` AND `UserFollowing`.`user_id` = 1)

但是CakePHP的可以绑定在飞行的关系,所以我加了current_user.id直接从会话的关联情况。

我不能在Rails的做到这一点,因为我不能把current_user.id的模型来描述条件:

user.rb
has_one :following, :class_name => 'UserFollowing', :conditions => {:user_id => current_user.id}

方法铌。 2

也许我可以解决这个使用:through ,但我找不到任何例子来得到相同的结果, users表从我做的关联。

方法铌。 3

难道它使用范围的Rails 3色器件,CURRENT_USER是不是在模型访问?

不知道,哪种方式是最好的...

Answer 1:

虽然它不是直接回答你的问题:考虑到创业板: acts_as_follower 。 我用了一个类似的情况,这似乎满足您的需求。 这有可能让任何跟随别的 - 检查出来...



Answer 2:

请专门阅读了这个问题第11章。 阅读整本书为AZ关于建立一个类似Twitter的应用程序。

Ruby on Rails的教程



Answer 3:

嗯,我已经发现了与范围来做到这一点的方式:

  # user.rb
  scope :with_relations, lambda { |current_user_id|
    has_one :user_following, :foreign_key => 'recipient_id', :conditions => {:user_id => current_user_id}
    where(:status => 1)
  }

  # users_controller.rb
  @users = User.with_relations(current_user.id).limit(30).order('last_action desc')


文章来源: Users list with follow/unfollow button