如何在Ruby on Rails中将视图中的变量传递给控制器​​?

时间:2012-03-07 18:55:55

标签: ruby-on-rails haml

这是我的index.html.haml:

= stylesheet_link_tag 'user'
.title
  %h1 Port Testing
  = form_tag('port_testing/test', method: 'get') do
    = text_field_tag :hostname, 'localhost', size: 50
    = check_box_tag('Port 80', '80')
    = label_tag('80')
    = check_box_tag('Port 443', '443')
    = label_tag('443')
    = check_box_tag('Port 28009', '28009')
    = label_tag('28009')
    = check_box_tag('Port 2195', '2195')
    = label_tag('2195')
    %button(type="submit") Test

在我的routes.rb中,我有这个:

  match 'port_testing/test', :controller => :port_testing, :action=> :test

这是我的port_testing_controller.rb:

class PortTestingController < ApplicationController
  def index

  end
  def test
      puts "\n"
      puts @params["hostname"]
  end
end

现在当我点击“测试”按钮时,我明白了:

  

开始GET“/ port_testing / test?utf8 =%E2%9C%93&amp; hostname = localhost”for 127.0.0.1
  在2012-03-07 13:51:33 -0500
   由PortTestingController处理#test作为HTML
   参数:{“utf8”=&gt;“G£ô”,“hostname”=&gt;“localhost”}

  在4ms内完成500内部服务器错误

     

NoMethodError(当你没想到它时,你有一个零对象!   您可能期望有一个Array实例   在评估nil时发生错误。[]):
   app / controllers / port_testing_controller.rb:7:在`test'

     

渲染供应商/ bundle / jruby / 1.9 / gems / actionpack-3.1.2 / lib / action_dispatch / middl   eware / templates / rescues / _trace.erb(6.0ms)
  渲染供应商/ bundle / jruby / 1.9 / gems / actionpack-3.1.2 / lib / action_dispatch / middl   eware / templates / rescues / _request_and_response.erb(3.0ms)
  渲染供应商/ bundle / jruby / 1.9 / gems / actionpack-3.1.2 / lib / action_dispatch / middl   救援/布局(155.0ms)内的eware / templates / rescues / diagnostics.erb

如何向控制器传递选中复选框以及在文本字段中输入的内容?

2 个答案:

答案 0 :(得分:2)

Rails中的params变量不是实例变量,因此您的控制器方法应该说:

def test
  puts "\n"
  puts params["hostname"]
end

答案 1 :(得分:0)

我知道我做到了..你可以通过循环遍历所有的参数...这样做..我敢打赌你的价值已经存在。