我有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=> ?) 
  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等)的情况下实现这一点,我将不胜感激.
Har*_*tty 77
声明一个模块
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
访问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
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")
  end
end
最后,指的是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) 
  end
end
Nat*_*ong 50
使用数据库是模型的工作.处理Web请求(包括了解当前请求的用户)是控制器的工作.
因此,如果模型实例需要知道当前用户,则控制器应该告诉它.
def create
  @item = Item.new
  @item.current_user = current_user # or whatever your controller method is
  ...
end
这假设Item有一个attr_accessorfor current_user.
如果用户创建了一个项目,该项目是否应该有一个belongs_to :user子句?这样你就after_update可以做到
History.create :username => self.user.username
| 归档时间: | 
 | 
| 查看次数: | 39420 次 | 
| 最近记录: |