ruby-on-rails - 如何在会话中存储变量?
问题描述
我正在开发的应用程序由每个可以拥有多个个人资料的用户组成(它应该像一个“家庭帐户”)。当用户登录时,他们可以选择他们想要使用的配置文件。
我将此信息保存在类变量中,但它不起作用。如果用户从另一个浏览器登录或设计并选择另一个配置文件,它会随处更改。这个想法是让不同的人访问同一个帐户并能够选择不同的个人资料,而不会改变其他人。
我研究并发现它应该保存在会话中,但我不知道该怎么做。如果保存在会话中,我还想知道如何修改它以及如何从控制器和/或视图访问它。
配置文件具有:“user_id”,该配置文件的所有者用户,和“名称”,由用户在创建配置文件时决定。
我不知道这是否有帮助,但我正在使用宝石“设计”。如果需要任何其他信息,请告诉我,以便我立即编辑帖子。
我正在分享下面的代码,这样你就可以看到我到目前为止所做的事情:
application_controller.rb
@@current_profile = nil
def set_current_profile
@@current_profile = Profile.find(params[:id])
puts "#{@@current_profile.name}" # debug
end
def return_current_profile
return @@current_profile
end
profile_controller.rb
def set_current_profile
super
redirect_to main_main_page_path
end
def return_current_profile
super
end
helper_method :return_current_profile
profile_select.html.erb
<div class="container">
<div class="list-group col-md-4 offset-md-4" align="center">
<% @profiles.all.each do |profile| %>
<%= link_to profile.name, profile, method: :set_current_profile, class: "list-group-item list-group-item-action" %>
<% end %>
</div>
</div>
路线.rb
post 'profiles/:id', to: 'profiles#set_current_profile', as: :set_current_profile
先感谢您。
解决方案
在 Rails 中,您可以创建新会话并获取如下会话:
# set the session
session[:key] = 'value'
# get the session
session[:key] #=> 'value'
如果要在会话中保存数组,可以这样做:
# save the ids
session[:available_user_ids] = available_user_ids.join(',')
# get the ids
session[:available_user_ids].split(',') #> [1,2,3]
推荐阅读
- spring-boot - spring boot 连接阿里巴巴 e-mapreduce kafka
- rest - 如何通过 bitbucket REST api 1.0 从所有分支获取所有提交?
- c# - .Net Nuget 包安装重新返回 ssl 错误
- aix - IBM PL/I:使用固定变量
- c++ - 如何在 qt 中包含菜单项的工具提示
- python - 我想在办公室找到一天中最忙的时间
- azure-storage - 在 Azure 存储上创建 PDF 后写入 PDF 文件内容
- ios - 快速为谷歌地图的圆圈添加标题
- c# - 如何使组合框可按关键字搜索
- php - 如何将值从存储库传递到 laravel 中的控制器