为了账号安全,请及时绑定邮箱和手机立即绑定

访问模型中的current_user

访问模型中的current_user

慕村9548890 2019-08-19 10:17:43
访问模型中的current_user我有3张桌子items (columns are:  name , type)history(columns are: date, username, item_id)user(username, password)当用户说“ABC”登录并创建新项目时,将使用以下after_create过滤器创建历史记录。如何通过此过滤器将此用户名“ABC”分配给历史记录表中的用户名字段。class Item < ActiveRecord::Base   has_many :histories   after_create :update_history  def update_history     histories.create(:date=>Time.now, username=> ?)    endend我在session_controller中的登录方法def login  if request.post?     user=User.authenticate(params[:username])     if user       session[:user_id] =user.id       redirect_to( :action=>'home')       flash[:message] = "Successfully logged in "     else       flash[:notice] = "Incorrect user/password combination"       redirect_to(:action=>"login")     end   endend我没有使用任何身份验证插件。如果有人能告诉我如何在不使用插件(如userstamp等)的情况下实现这一点,我将不胜感激。
查看完整描述

3 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

Rails 5

声明一个模块

module Current
  thread_mattr_accessor :userend

分配当前用户

class ApplicationController < ActionController::Base
  around_action :set_current_user  def set_current_user    Current.user = current_user    yield
  ensure
    # to address the thread variable leak issues in Puma/Thin webserver
    Current.user = nil
  end             end

现在您可以将当前用户称为 Current.user

有关thread_mattr_accessor的文档

Rails 3,4

访问current_user模型内部并不常见。话虽如此,这是一个解决方案:

class User < ActiveRecord::Base
  def self.current    Thread.current[:current_user]
  end

  def self.current=(usr)
    Thread.current[:current_user] = usr  endend

current_user在a around_filter中设置属性ApplicationController

class ApplicationController < ActionController::Base
  around_filter :set_current_user  def set_current_user    User.current = User.find_by_id(session[:user_id])
    yield
  ensure
    # to address the thread variable leak issues in Puma/Thin webserver
    User.current = nil
  end             end

设置current_user成功后的身份验证:

def login  if User.current=User.authenticate(params[:username], params[:password])
    session[:user_id] = User.current.id
    flash[:message] = "Successfully logged in "
    redirect_to( :action=>'home')
  else
    flash[:notice] = "Incorrect user/password combination"
    redirect_to(:action=>"login")
  endend

最后,指的是current_userupdate_historyItem

class Item < ActiveRecord::Base
  has_many :histories
  after_create :update_history  def update_history
    histories.create(:date=>Time.now, :username=> User.current.username) 
  endend


查看完整回答
反对 回复 2019-08-19
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

如果用户创建了一个项目,该项目是否应该有一个belongs_to :user子句?这样你就after_update可以做到

History.create :username => self.user.username


查看完整回答
反对 回复 2019-08-19
  • 3 回答
  • 0 关注
  • 623 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信