Reputation: 743
I want to let users in my application be able to click a button that says "Save current page" and be able to access it later to take them back to that same page no matter what unless they save a different page.
I believe doing it through a cookie is the best way?
Here's what I've tried:
homepage view:
<%= link_to "Return to your last question", cookies[:saved_url], :class => "button is-info" %>
controller:
def resume
cookies.permanent[:saved_url] = request.original_url
redirect_to :saved_url
end
view:
<%= link_to 'Save Progress', users_resume_path, method: :post %>
route:
post 'users/resume'
EDIT: all of this is occuring within a custom method
def tagged
@mcqs = MultipleChoiceQuestion.with_tag(params[:tag]).order("created_at DESC").published.paginate(:page => params[:page], :per_page => 1)
authorize @mcqs
cookies.permanent[:saved_url] = request.original_url
end
my problem is, i can't use the iVar that was proposed within a new custom method, so adding another method doesn't seem to be working
Upvotes: 0
Views: 56
Reputation: 102212
This is how I would solve it.
class AddCurrentQuestionToUser < ActiveRecord::Migration[5.2]
def change
add_reference :users, :current_question, foreign_key: { to_table: :questions }
end
end
class User < ApplicationRecord
belongs_to :current_question, class_name: 'Question'
end
I'm assuming here that you have a current_user
method.
# config/routes.rb
resources :questions do
patch :current
end
class QuestionsController
# PATCH /questions/:id/current
def current
@question = Question.find(params[:id])
if current_user.update(current_question: @question)
redirect_to @question, success: 'Current question updated.'
else
redirect_to @question, error: 'Could not update question.'
end
end
end
You can create a button to update this by:
<%= button_to 'Save question', question_current_path(@question), method: :patch %>
If you then want to link to the users current question you can do it by:
<%= link_to "Resume", current_user.current_question %>
The whole redirect step is completely redundant.
Upvotes: 2