gpt4 book ai didi

ruby-on-rails - 访问模型中的current_user

转载 作者:行者123 更新时间:2023-12-03 07:21:51 26 4
gpt4 key购买 nike

我有3张 table

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=> ?)
end
end

我在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
end
end

我没有使用任何身份验证插件。如果可能的话,如果有人能告诉我如何在不使用插件(如 userstamp 等)的情况下实现这一目标,我将不胜感激。

最佳答案

rails 5

声明模块

module Current
thread_mattr_accessor :user
end

分配当前用户

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
end
end

ApplicationControlleraround_filter 中设置 current_user 属性。

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")
end
end

最后引用Itemupdate_history中的current_user

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

关于ruby-on-rails - 访问模型中的current_user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2513383/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com