Chen Shirley
Chen Shirley

Reputation: 43

rails 4 - update attribute with browser's back button only when leaving a webpage

I am trying to track which page user visit and when user access and leave. I store access time successfully by following the advise in how to change database values with a link. Here is the flow:

But when I want to apply this method to store leave time, I got some problems. I want to update the time when user leave the page to the record I just create. The above method just work while user click the "back" button which I create in webpage.

If user click browser's back button, it will do nothing. I guess the reason why update_attribute doesn't work is that ruby on rails do not call the action in controller while browser's back button been clicked...... How can it work while user click browser's back button?

The flow might be something like this:

review.html.erb

# while click the "Back" button, redirect to "store" and update leave time for the record just create
<%= button_to "Back", {:action=>"stores", :user=>@product.user, :order=>@product.order}, :method=>:get %>

controller.rb

def store
    @user = params[:user]
    @order = params[:order]
    @lastevent = Event.where(:user=>@user).order("id").last
    @lastevent.update_attributes!(:leave_time => Time.now)
end

Upvotes: 1

Views: 870

Answers (1)

matanco
matanco

Reputation: 2129

Use javascript to solve it:

$(window).on("navigate", function (event, data) {
  var direction = data.state.direction;
  if (direction == 'back') {
    <% update_method_helper %>
  }      
});

use it as a partial and call this partial in every page you want to use it(if you want all pages use it in the layout).

Upvotes: 0

Related Questions