我正在尝试创建一个基于会话值呈现特定视图的应用程序。但是,我无法存储会话值。
我的控制器是这样的:
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
我的观点是这样的(名为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>
在routes.rb
中,question_path被定义为:
resources :question do
collection do
get :next_page
end
end
但是,session[:state]
总是Nil
,为什么?
注意:这个问题纯粹是关于Ruby on Rails的工作方式,我已经省略了网站本身的大部分细节,只留下了与问题相关的内容。
答案 0 :(得分:1)
不确定您是如何触发next_page_path但是提供您给出的信息可以在问题路径中设置param [:state]并根据该设置设置会话。
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>