【问题标题】:How to store a variable in session?如何在会话中存储变量?
【发布时间】:2020-03-12 04:49:06
【问题描述】:

我正在开发的应用由可以拥有多个个人资料的用户组成(它应该类似于“家庭帐户”)。当用户登录时,他们可以选择他们想要使用的配置文件。

我将此信息保存在一个类变量中,但它不起作用。如果用户从另一个浏览器登录或设计并选择另一个配置文件,它会随处更改。这个想法是让不同的人访问同一个帐户并能够选择不同的个人资料,而不会更改为其他人。

我研究并发现它应该保存在会话中,但我不知道该怎么做。如果保存在会话中,我还想知道如何修改它以及如何从控制器和/或视图访问它。

配置文件具有:“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>

routes.rb

   post 'profiles/:id', to: 'profiles#set_current_profile', as: :set_current_profile

提前谢谢你。

【问题讨论】:

    标签: ruby-on-rails ruby session session-variables


    【解决方案1】:

    在 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多