Joël Abrahams
Joël Abrahams

Reputation: 381

Unable to get session value

I am trying to create an application which renders a certain view based on a session value. However, I am unable to store the session value.

My controller is as such:

class MyController < ApplicationController
  def question
    if session[:state].nil?
      session[:state] = 'question_one'
    end
  end

  def next_page
    # state pattern would be much better, this is a bit ugly
    if session[:state].nil? || session[:state] == 'question_one'
      session[:state] = 'question_two'
    elsif session[:state] == 'question_two'
      session[:state] = 'question_one'
    end
  end
end

My view is a such (named question.html.erb):

<h1>Question</h1>

<div align="center">
    <% if (session[:state]).to_s == 'question_one' %>
        <%= render partial: 'layouts/question_one' %>
    <% else %>
        <%= render partial: 'layouts/question_two' %>
    <% end %>
</div>

<div class="buttons">
    <%= link_to "Next", question_path, class: "btn btn-large btn-primary" %>
</div>

And in the routes.rb, question_path is defined as such:

resources :question do
    collection do
        get :next_page
    end
end

However, session[:state] is always Nil, why?

Note: This question is purely about how Ruby on Rails works, the I have omitted most of the details of the site itself and left only what is relevant to the question.

Upvotes: 0

Views: 108

Answers (1)

David Gross
David Gross

Reputation: 1873

Not sure how you are triggering next_page_path but giving the information you have given you could set param[:state] in the question path and set the session based off that.

 def question
  # session[:state] = 'semantic_recognition_state'
  # not sure why you are setting 'semantice_recognition_state' 

  if params[:state].nil? && session[:state].nil?
    session[:state] = 'question_one'
  elsif params[:state].nil? && session[:state].present?
    session[:state]
  else 
    session[:state] = params[:state]
  end
end


<div class="buttons">
  <%= link_to "Next", question_path(state: 'question_two'), class: "btn btn-large btn-primary" %>
  <%= link_to "Back", question_path(state: 'question_one'), class: "btn btn-large btn-primary" %>
</div>

Upvotes: 1

Related Questions