2013-04-10 47 views
0

我是ROR的初学者。我遇到了一个问题,那就是当我在一本书上测试代码时。我跟着它分阶段,但错误显示...在CaculatorController#Ruby on Rails:NoMethodError

NoMethodError计算

undefined method `[]=' for nil:NilClass 

Rails.root:/家庭/ toth4321 /计算器

app/controllers/caculator_controller.rb:4:in `set_charset' 

控制器

class CaculatorController < ApplicationController 
    before_filter:set_charset 
    def set_charset 
    @headers['Content-Type'] = 'text/html; charset=GB2312' 
    end 

    def calculate 
    if request.post? 
     arg1 = convert_float(:arg1) 
     arg2 = convert_float(:arg2) 
     op = convert_operator(:operator) 
     @result = op.call(arg1, arg2) 
    end 
    end 

    private 
    def convert_float(name) 
    Float (params[name]) 
    end 

    def convert_operator(name) 
    case params[name] 
     when "+" then proc {|a,b| a+b} 
     when "-" then proc {|a,b| a-b} 
     when "*" then proc {|a,b| a*b} 
     when "/" then proc {|a,b| a/b} 
    end 
    end 
end 

V iews

<html> 
    <head> 
    <title>簡單的網頁計算器</title> 
    </head> 
    <body> 
    <%= form_tag(:action => :calculate) %> 
     <%= text_field_tag(:arg1, @params[:arg1], :size =>3) %> 
     <%= select_tag(:operator, options_for_select(%w{+ - * /})), @params[:operator])) %> 
     <%= text_field_tag(:arg2, @params[:arg2], :size =>3) %> 
     <%= submit_tag("送出") %> 
    <% end_form_tag %> 
    <b><%= @result %></b> 
    </body> 
</html> 

有人可以帮助我吗? 非常感谢!

回答

0

不知道@headers做什么,但据我所知,你没有在任何地方定义它。尝试:

def set_charset 
    @headers = {'Content-Type' => 'text/html; charset=GB2312'} 
    end 
+0

它显示这个错误 '/home/toth4321/calculator/app/controllers/calculator_controller.rb:4:语法错误,意想不到的 '=',希望keyword_end @headers = ['内容类型'] ='text/html;字符集= GB2312' ' – 2013-04-10 16:13:34

+0

不是'=',而是'=>' – Zippie 2013-04-10 16:14:29

0

@headers取出@,因为它不是一个实例变量,而是为response.headers散列的委托方法:

headers['Content-Type'] = 'text/html; charset=GB2312' 
0

请尝试通过添加以下代码运行。

before_filter :set_charset 
def set_charset 
    @headers["Content-Type"] = "text/html; charset=GB2312" 
end