0

私はRORの初心者です.1冊の本でコードをテストするときに問題に直面しました. 段階的にフォローしていますが、エラーが表示されます...

CaculatorController#calculate の NoMethodError

undefined method `[]=' for nil:NilClass

Rails.root: /home/toth4321/calculator

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

ビュー

<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("送出") %&gt;
    <% end_form_tag %>
    <b><%= @result %></b>
  </body>
</html>

誰かが私を助けることができますか?どうもありがとう!

4

3 に答える 3

0

何が何をするのかわかりませんが@headers、私が見る限り、どこにも定義していません。試す:

  def set_charset
    @headers = {'Content-Type' => 'text/html; charset=GB2312'}
  end
于 2013-04-10T16:03:52.410 に答える
0

以下のコードを追加して実行してみてください。

before_filter :set_charset
def set_charset
    @headers["Content-Type"] = "text/html; charset=GB2312" 
end
于 2013-08-27T13:27:57.387 に答える
0

インスタンス変数ではなく、ハッシュのデリゲート メソッドであるため、 @from を削除します。@headersresponse.headers

headers['Content-Type'] = 'text/html; charset=GB2312'
于 2013-04-10T21:37:05.480 に答える