在我看来,我有远程linkaction,它设置会话变量:
%ul
%li
= link_to "Ростов-на-Дону", set_city_path(city_id: 1), remote: true, class: "city-selector-list-city"
%li
= link_to "Ставрополь", set_city_path(city_id: 2), remote: true, class: "city-selector-list-city"
%li
= link_to "Краснодар", set_city_path(city_id: 3), remote: true, class: "city-selector-list-city"
和方法:
def set_city_session
#binding.pry
if [1, 2, 3].include? params[:city_id].to_i
session[:city_id] = params[:city_id].to_i
if session[:city_id] == 1
@city_id = "Ростов-на-Дону"
end
if session[:city_id] == 2
@city_id = "Ставрополь"
end
if session[:city_id] == 3
@city_id = "Краснодар"
end
end
#binding.pry
end
视图:
$("#city-name-link").text("#{escape_javascript(@city_id)}");
window.location.reload();
但是当我点击其他链接或进入其他页面时,我看到,我的会话被“删除”,没有存储值,例如,如果我设置= 3,我看到它是= 1.但为什么?如何在会话中存储价值?
UPD:
布局:
- if session[:city_id] == 1
Ростов-на-Дону
- if session[:city_id] == 2
Ставрополь
- if session[:city_id] == 3
Краснодар
答案 0 :(得分:0)
要在会话中存储值,您必须在会话中设置值。目前,您正在设置实例变量,如果您重新加载页面,这些变量将会丢失:
更好的方法是直接设置会话变量,或者不在ajax成功时重新加载Window:
def set_city_session
#binding.pry
if [1, 2, 3].include? params[:city_id].to_i
session[:city_id] = params[:city_id].to_i
if session[:city_id] == 1
session[:city_name] = "Ростов-на-Дону"
end
if session[:city_id] == 2
session[:city_name] = "Ставрополь"
end
if session[:city_id] == 3
session[:city_name] = "Краснодар"
end
end
#binding.pry
end
$("#city-name-link").text("#{escape_javascript(session[:city_name])}");
如果您想设置"默认"会议的价值,你最好做这样的事情:
#app/controllers/application_controller.rb
Class ApplicationController < ActionController::Base
before_action :set_session
private
def set_session
session[:city_id] ||= "1"
session[:city_name] ||= "Ростов-на-Дону"
end
end
答案 1 :(得分:0)
您的set_city_session
方法无法返回任何内容,因此当您点击链接时我认为您遇到ActionView::MissingTemplate
错误,这会阻止会话变量设置。检查你的JS控制台上的HTML响应,你也可能会在那里看到它。
如果您真的不需要返回任何内容(甚至是成功/错误标记),您可以将其添加到set_city_session
方法中,它会起作用:
render :nothing => true