0

I have a piece of html like this:

    <div class="row well">
      <form method="POST">
        <ol id="velArea">
          <li>  Layer velocity: (m/s) <input type="text" name="source[]"> </li>
        </ol>
        <input type="button" value="Add another layer" name="velocity" onClick="addVel('velArea');">
      </form>
    </div>

and a javascript function that adds html to the area

    function addVel(area)
    {
      var field_area = document.getElementById(area);
      field_area.innerHTML += "<li>  Layer velocity: (m/s) <input type='text' name='velocity'> <a style='cursor:pointer;color:grey;' onclick='this.parentNode.parentNode.removeChild(this.parentNode);''>delete</a> </li>";
    }

I need to read the value of each input field in a rails function. And have no idea about how to do that. I've lost days going through active model in rails, thinking that was the way until I finally figured out that is better to keep the browser-related and server related things separated. So I learned a little javascript and made a few functions. Yes, I'm new to web development. I'm using rails 3.2.

The function that I want to uses the fields info is called by a button:

     <%= button_to "Run single inversion", {:action => "my_func", }, {:remote => true, :form => { "data-type" => "json" }, :class => "btn btn-primary"} %>

and the function on the controller is:

    def my_func
      render :nothing => true
      vel = params[:velocity]
      puts vel.class
      puts 'Hi'
    end

the output I get is

    NilClass
    Hi

so I'm clearly not passing the arguments right. I'm guessing I need to pass the velocity array in the post method when I use the button_to, but have no idea about how to do that.

Also, I'm need the value of the input, not anything database oriented so I cannot look it up using activeRecord properties.

4

2 回答 2

1

在您的 Rails 控制器中,您应该能够params[:model_name]在 javascript 将表单提交给您需要它使用的任何方法时访问。您还可以访问一个params[:id]params[:firstname]

我也有点困惑你在做什么 <input type='text'> </input>

没有名称属性,模型需要该属性来识别它并将其值与列相关联。它也不是正确的输入方式。

<input type="text" name="column_name"/>

更接近你想要的

于 2012-11-03T17:40:47.103 回答
1

我不确定你的代码为什么这么复杂。但基本上有一些东西不是 RailsWay。首先,您应该看看Rails Form Helpers。如果您使用约定,您将收到如下的 params 哈希:

params[:velocities][:velocity]
params[:velocities][:source]

表单标签看起来像这样:

<input type="text" name="velocities[velocity]" id="velocities_velocity" value="">
<input type="text" name="velocities[source]" id="velocities_source" value="">

在上面的代码中,您期望 vel 的值。产生的 NilClass 是因为 params[:velocity] 中有 nil,所以 vel 是 nil。您应该检查以下内容:

puts params.inspect

或者在运行 Rails 应用程序时查看日志。

请重新检查按钮和输入字段的名称属性。它们的名称属性都是“速度”。如果按钮是提交的后者,那么 params[:velocity] 的值肯定是空的......

于 2012-11-03T23:38:52.290 回答