How to show who has visited your profile?

2019-06-07 06:17发布

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.

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?

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-07 07:04

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

and User model:

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

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

And vualá!

Now you can user something like this:

    current_user.visitors

Or with some conditions:

    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

Hope it helped!

查看更多
登录 后发表回答