Ruby on rails 访问控制器中的当前用户
我正在尝试访问控制器中当前用户的属性Ruby on rails 访问控制器中的当前用户,ruby-on-rails,authentication,Ruby On Rails,Authentication,我正在尝试访问控制器中当前用户的属性 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_use
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
ApplicationController包含SessionHelper
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
class ApplicationController
这是我的会话控制器
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
class sessioncontroller
我认为助手仅对视图可用。尝试将其放在控制器顶部附近:
include sessionHelper
将您的代码放入应用程序控制器,并将其标记为helper\u method
,这样您就可以在helper
和controller
中使用该方法
helper_method :current_user
def current_user=(user)
@current_user = user
end
编辑我的帖子后,SessionHelper已包含在ApplicationController中。如果在视图中调用sign_,则这就是原因。请注意,当前用户是通过查看cookie找到的,并且在sign_in中设置了记住令牌cookie。不过,我假设这只是第一次访问时的问题。我不在视图中调用它,而是在SessionController中调用create。我已经把它包括在上面了。假设cookies[]以明显的方式工作。。。。对不起,我被难住了。找出cookies[]是否确实包含您认为它的功能,检查在当前用户方法中生成的SQL。这就是我现在能想到的。是的,饼干起作用了。登录/注销正在工作,并在视图中管理状态。就是这个控制器,我遇到了麻烦。无论如何谢谢你!您能否确认cookies[:Rememory_token]存在且正确,并且存在于用户表中?是的。正在将其保存到用户表中。所有测试均通过,但我调用控制器中的当前用户额定值(NoMethodError)时除外。
helper_method :current_user
def current_user=(user)
@current_user = user
end