L
L
lavezzi12015-08-19 16:59:18
Ruby on Rails
lavezzi1, 2015-08-19 16:59:18

@User.last_seen_at best way?

Hello!
It is interesting to know your opinion about this piece of code, as well as to find out alternatives for solving this problem.
There is one problem here, if you go to the profile of a person who did not log in after adding this function, it throws an error

undefined method `>' for nil:NilClass
How is this possible to solve?
application_controller.rb
before_action :set_last_seen_at, if: proc { user_signed_in? && (session[:last_seen_at] == nil || session[:last_seen_at] < 15.minutes.ago) }



  private
  def set_last_seen_at
    current_user.update_attribute(:last_seen_at, Time.now)
    session[:last_seen_at] = Time.now
  end

view
= time_ago_in_words(@user.last_seen_at)
In database
add_column :users, :last_seen_at, :datetime

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jeiwan, 2015-08-19
@Jeiwan

time_ago_in_words takes a date and @user.last_seen_at returns nil. You need to do something like this:
Or
PS

(session[:last_seen_at] == nil || session[:last_seen_at] < 15.minutes.ago)
it is better to do this check in the set_last_seen_at method - this way the code will be better read.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question