訪問模型中的current_user我有3張桌子items (columns are: name , type)history(columns are: date, username, item_id)user(username, password)當(dāng)用戶說“ABC”登錄并創(chuàng)建新項(xiàng)目時(shí),將使用以下after_create過濾器創(chuàng)建歷史記錄。如何通過此過濾器將此用戶名“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我沒有使用任何身份驗(yàn)證插件。如果有人能告訴我如何在不使用插件(如userstamp等)的情況下實(shí)現(xiàn)這一點(diǎn),我將不勝感激。
3 回答

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
Rails 5
聲明一個(gè)模塊
module Current thread_mattr_accessor :userend
分配當(dāng)前用戶
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
現(xiàn)在您可以將當(dāng)前用戶稱為 Current.user
有關(guān)thread_mattr_accessor的文檔
Rails 3,4
訪問current_user
模型內(nèi)部并不常見。話雖如此,這是一個(gè)解決方案:
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
中設(shè)置屬性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
設(shè)置current_user
成功后的身份驗(yàn)證:
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_user
在update_history
的Item
。
class Item < ActiveRecord::Base has_many :histories after_create :update_history def update_history histories.create(:date=>Time.now, :username=> User.current.username) endend

慕妹3242003
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果用戶創(chuàng)建了一個(gè)項(xiàng)目,該項(xiàng)目是否應(yīng)該有一個(gè)belongs_to :user
子句?這樣你就after_update
可以做到
History.create :username => self.user.username
- 3 回答
- 0 關(guān)注
- 719 瀏覽
添加回答
舉報(bào)
0/150
提交
取消