新手问题 Rails controller 问题

tangier · 2013年03月05日 · 最后由 zlx_star 回复于 2013年03月06日 · 2025 次阅读

问题 1 :

class  < Action::Base
    def current_user
       ...
    end
end

class Home < 
   def index
      current_user # 为什么 的方法还能在Home里面用?
   end
end

问题 2:

require "spec_helper"

class  < Action::Base
  protect_from_forgery

  def current_user
    session[:user_id]
  end
end

describe ApplicationController do
  describe "current_user" do
    it "should return nil if no one is logged in" do
      subject.current_user.should be_nil
    end
    it "should return currently logged in user" do
      hash = {user_id: "my_id"}
      subject.should_receive(:session).and_return hash
      subject.current_user.should == "my_id"
    end
  end
end

NoMethodError:: `current_user' called for #<? 为什么会在测试中找不到实例方法?

问题1:

HomeController < ApplicationController 表示前者继承后者,可用其非私用方法

问题2:

NoMethodError: protected method `current_user' called for #<ApplicationController?

提示十分清楚,current_user 是 ApplicationController 中的保护方法,不能实例调用,只能继承使用。

#1 楼 @shatle 问题 2:我把 proctected 去掉依然还是 NoMethodError, 为什么呢?

#2 楼 @tangier 建议先把代码格式化,按 M 查看帮助

#3 楼 @zlx_star ok,格式化好,谢谢提醒...

#4 楼 @tangier

  • 可以贴出详细的错误信息吗?
  • ApplicationController 不是应该继承 ActionController::Base 吗?
需要 登录 后方可回复, 如果你还没有账号请 注册新账号