简体   繁体   English

如何在 Ruby/Rails 中显示 session 变量的值?

[英]How do I display the value of a session variable in Ruby/Rails?

First I don't know if I'm declaring a session variable correctly.首先,我不知道我是否正确声明了 session 变量。 Also, I put it in the application controller, because I know it will run.另外,我把它放在应用程序 controller 中,因为我知道它会运行。 If there is a better place to put this, then please let me know.如果有更好的地方放这个,请告诉我。 The desired outcome is a user selects the team they want all their work to save to during the session.期望的结果是用户在 session 期间选择他们希望将所有工作保存到的团队。 Then when objects are saved they use the session variable:current_team instead of:current_user.然后当保存对象时,他们使用 session 变量:current_team 而不是:current_user。 By default on creation a team will be created for each new user.默认情况下,在创建时将为每个新用户创建一个团队。 That is why I'm querying for the first team for each user.这就是为什么我要为每个用户查询第一个团队。 During the session I plan for the user to select the team they are working/contributing for and the selection persist until they change it.在 session 期间,我计划让用户 select 为他们工作/贡献的团队,并且选择一直存在,直到他们改变它。

application_controller.rb application_controller.rb

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  before_action :set_current_team

  def set_current_team
    return unless session[:current_team]
    session[:current_team] = Team.first.where(user_id: current_user).id
  end


end

index.html.erb索引.html.erb

<p><%= session[:current_team] %></p>

output output

Processing by PagesController#index as HTML
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ /home/dev/.rbenv/versions/2.5.2/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Rendering pages/index.html.erb within layouts/application
  Rendered pages/index.html.erb within layouts/application (0.5ms)
  Rendered shared/_navigation.html.erb (2.9ms)
Completed 200 OK in 172ms (Views: 168.3ms | ActiveRecord: 0.4ms)

My models are Team, User, and a join table Team_member.我的模型是 Team、User 和一个联接表 Team_member。 team_member.rb团队成员.rb

  belongs_to :user
  belongs_to :team
  belongs_to :role
end

team.rb团队.rb

  has_many :team_members
  has_many :users, through: :team_members
  has_many :roles, through: :team_members
end

Once you have session[:current_team] , you can save it to a variable in any controller.拥有session[:current_team]后,您可以将其保存到任何 controller 中的变量中。 Say for instance in the teams controller, you can do: @current_team = session[:current_team] .例如在团队 controller 中,你可以这样做: @current_team = session[:current_team] Then in the view you can use @current_team .然后在视图中您可以使用@current_team

I assume one user can be part of multiple teams and (obviously) one team has many users, your relation would be roughly like this我假设一个用户可以是多个团队的一部分,并且(显然)一个团队有很多用户,你的关系大概是这样的

class User < ApplicationRecord
  has_and_belongs_to_many :teams
end

class Team < ApplicationRecord
  has_and_belongs_to_many :users
end

You are already in right direction but I made little changed to set_current_team and added accessor method to get current team instance.您已经朝着正确的方向前进,但我对set_current_team几乎没有更改,并添加了访问器方法来获取当前团队实例。

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  before_action :set_current_team

  helper_method :current_team

  def set_current_team
    return unless session[:current_team]
    session[:current_team] = current_user.teams.first.id
  end

  def current_team
    @_team ||= Team.find(session[:current_team])
  end
end

The current_team method uses memoization technique to cache the current team during the request so that if you call current_team multiple times during a request, it will not call the DB again to get the team record. current_team方法使用memoization 技术在请求期间缓存当前团队,这样如果您在请求期间多次调用current_team ,它就不会再次调用数据库来获取团队记录。

I strongly recommend to read this article 4 Simple Memoization Patterns in Ruby .我强烈推荐阅读这篇文章4 Simple Memoization Patterns in Ruby

Also notice helper_method macro above the set_current_team which makes this helper method available to your view as well.另请注意helper_method上方的set_current_team宏,它使您的视图也可以使用此帮助方法。

so following will work on your index所以以下将适用于您的索引

<p><%= current_team %></p>

as well as across all controllers as all controllers inherits from ApplicationController以及跨所有控制器,因为所有控制器都从ApplicationController继承

update set_current_team method to set_current_team方法更新为

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  before_action :set_current_team

  # only set the session[:current_team] if it is nil (when user login)
  def set_current_team
    session[:current_team] ||= current_user.teams.first.id
  end

  # to access current_team
  def current_team
    @current_team ||= Team.find(session[:current_team])
  end
end

set session[:current_team] to user selected team id in controller#action that handles the requestsession[:current_team]设置为用户在处理请求的控制器#action 中选择的团队 ID

set session[:current_team] to nil when user logout用户注销时将session[:current_team]设置为nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在rails上的ruby中为实例变量附加一些值? - How do i append some value to an instance variable in ruby on rails? 如何在Ruby on Rails的会话对象中显示值? - How can i display values in session object in Ruby on Rails? 如何在Ruby on Rails中自动更新并在视图中显示变量? - How could I automatically update and display a variable in a view, in Ruby on Rails? 如何使Ruby on Rails将数据显示为Bootstrap网格? - How do I get Ruby on Rails to display data as a Bootstrap grid? 如何在Ruby on Rails中显示已删除元素的名称? - How do I display the name of a deleted element in Ruby on Rails? Ruby on Rails如何显示与特定行关联的数据 - Ruby on rails How do I display data associated with a specific row 如何显示名称空间的验证错误? Ruby on Rails - How do I display validation errors with namespaces? Ruby on rails 如何在轨道上的 ruby 的不同位置显示上传的图像? - How do i display uploaded images at different locations in ruby on rails? 如何在 Rails 上的 Ruby 中显示数据库中的图像文件? - How do I display image file from database in Ruby on Rails? 如何在Ruby on Rails中将会话值转换为字符串? - How to convert session value to string in Ruby on Rails?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM