如何显示谁访问了您的个人资料? [英] How to show who has visited your profile?

查看:50
本文介绍了如何显示谁访问了您的个人资料?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个应用程序,其中包含拥有用户个人资料的用户,我有一个访问者标签,我想向访问过他们个人资料的用户显示.

So, I have an app with Users who have user profiles and I have a visitors tab that I'd like to show the user who has visited their profile.

我怎样才能做到这一点?我现在有一个用户模型,我猜我可能需要使用 HMT?IE.一个用户通过 user_visitors 或其他方式有_many 访问者.. 你能澄清一下如何做到这一点吗?

How might I accomplish this? I have a user model at the moment, I'm guessing I'd need to use a HMT perhaps? I.e. A user has_many visitors through user_visitors or something.. Can you please clear up how this can be done?

推荐答案

您可以创建一个连接模型,命名为Visit

You can create a join model, named Visit

    class Visit < ActiveRecord::Base
      belongs_to :user
      belongs_to :visitor, class_name: 'User', foreign_key: 'visitor_id'
    end

和用户模型:

    class User < ActiveRecord::Base
      has_many :visits
      has_many :visitors, through: :visits
    end

要创建访问,请将您的控制器 users_controller 置于 before_action 中:

To create visits, put your controller users_controller a before_action:

    def create_visit
      @user.visits.create(visitor: current_user)
    end

或者,如果您不想重复访问:

or, if you dont want repeated visits:

   def create_visit
     @user.visits.where(visitor: current_user).first_or_create
   end

还有哇!

现在您可以使用以下内容:

Now you can user something like this:

    current_user.visitors

或者有一些条件:

    current_user.visitors.where('created_at > ?', 1.month.ago)

你也可以为你的关系设置条件:

you also can put conditions on you relation:

    class User < ActiveRecord::Base
      ...
      has_many :recent_visitors, through: :visits, source: :visitor, conditions: [ "created_at > ?", 1.month.ago ]
      ...
    end

希望有帮助!

这篇关于如何显示谁访问了您的个人资料?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆