我正在尝试访问控制器内current_user的属性。
class MatchfinderController < ApplicationController
def c(value, t_array)
t_array.min{|a,b| (value-a).abs <=> (value-b).abs }
end
def show
peeps = User.find(:all, :conditions => ["id != ?", current_user.id])
user_a = []
peeps.each do |user|
user_a.push user.rating
end
closest_rating = c(current_user.rating, user_a)
@opponent = User.find(:all, :conditions => ["id != ? AND rating = ? ", current_user.id, closest_rating])
end
end
current_user正在视图中工作,但在控制器中返回nil。
这是我的SessionsHelper。
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
def signed_in?
!current_user.nil?
end
end
SessionsHelper包含在ApplicationController
中class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
这是我的SessionsController
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
sign_in user
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render "new"
end
end
def destroy
cookies[:remember_token] = nil
redirect_to root_url, notice: "Logged out!"
end
end
答案 0 :(得分:2)
将您的代码放入应用程序控制器并将其标记为helper_method
,这样您就可以在helper
以及controller
helper_method :current_user
def current_user=(user)
@current_user = user
end
答案 1 :(得分:0)
我认为助手只适用于视图。尝试将它放在控制器顶部附近:
include SessionsHelper