1

我正在尝试访问我的控制器中有关 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
4

2 回答 2

2

将您的代码放在应用程序控制器中并将其标记为helper_method这样您就可以在两者中使用该helper方法controller

helper_method :current_user

def current_user=(user)
  @current_user = user
end
于 2012-09-21T05:00:52.427 回答
0

我认为助手仅适用于视图。试着把它放在你的控制器顶部附近:

include SessionsHelper

于 2012-09-21T04:02:58.967 回答