将RoR form_for与collection_select一起使用

时间:2016-07-03 05:50:51

标签: javascript jquery ruby-on-rails ajax

在form_for @estimate中,我使用collection_select给出了一个' lead'中潜在客户名称的下拉列表。表

    <%= form_for(@estimate) do |f| %>

    <div class="field">
      <%= f.label "Lead" %><br>
      <%= f.collection_select :lead_id, @leads, :id, :full_name, prompt: true %>
    </div>
    ...

select标签的选项正确填充了潜在客户。我使用jQuery的.getJSON方法从所选的选项中检索数据

    $(document).on('change', 'select#estimate_lead_id', function(e) {
      var url = "/leads";
      var data = {
        id: $(this).val()
      };
      $.getJSON(url, data, function (data, status) {        
        if (status === 200) {
          return data
          console.log(data);
          alert("THIS IS WORKING!");        
        };
      });
     });

然而,我无法让它发挥作用。这是我的服务器日志 - 它似乎正在访问数据库。

    Started GET "/leads?id=23" for 127.0.0.1 at 2016-07-02 23:29:29-    0500
    Processing by LeadsController#index as JSON
    Parameters: {"id"=>"23"}
    Lead Load (1.1ms)  SELECT "leads".* FROM "leads"
    Rendered leads/index.html.erb within layouts/application (10.4ms)
    User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
    Completed 200 OK in 51ms (Views: 47.6ms | ActiveRecord: 1.8ms)

我从头数据库中选择id = 23的名称,但没有记录到控制台,也没有警报。我想使用数据来填充估算表单中的字段。我做错了什么?

1 个答案:

答案 0 :(得分:0)

在处理异步任务之前,我遇到了同样的问题。 我所做的是分别调用onchange函数,我在select标签中调用它:

它看起来像这样:

<select onchange="myfunction(parameterIfneeded)"> 
....
</select>

然后在我的js函数中:

function myfunction(param) {
       ..............
       .......
     //PROCESS your AJAX here
}
相关问题