从数据库中搜索记录并将其添加到列表中

时间:2015-12-01 13:58:06

标签: javascript ruby-on-rails-4

我是铁轨上红宝石的初学者。 我想做的是:

  1. 创建搜索产品的输入搜索。
  2. 然后,我点击提交按钮,此产品将在下面的列表中显示。
  3. 我搜索了另一个产品,它将被添加到我的列表中。
  4. 最后,我将列出搜索到的产品。
  5. 
    
    <script type="text/javascript">
        
    var foodList = [];
    
    function addToFood () {
        var addFood = document.getElementById('addFood').value;
        var addQuantity = document.getElementById('addFood').value;
    
        foodList.push(addFood + "  " + addQuantity );
    
        
        for (i = 0; i < foodList.length; i++)	{
            var newFood = "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
        };
        document.getElementById('foods').innerHTML += newFood;
    
        document.getElementById('addQuantity').value = '';
        document.getElementById('addFood').value = '';
    
    }
    
    
    function removeRecord (i) {
        foodList.splice(i, 1);
        var newFood = "";
        // re-display the records from foodList the same way we did it in addToFood()
        for (var i = 0; i < foodList.length; i++) {
            newFood += "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
        };
        document.getElementById('foods').innerHTML = newFood;
    }
    
    </script> 
    &#13;
    <%= form_tag akala_health_path, :method => 'get', :id => "products_search" do %>
      <p>
        Product name
        <%= text_field_tag :search, params[:search] , :id => "addFood"%></br>
        <%= submit_tag "Search", :name => nil %>
      </p>
      
    <% end %>
      
    <table id="products">
      <tr>
        <th>Product name</th>
        <th>Product code</th>
        <th>Product quantity</th>
        <th></th>
      </tr>
      <% if @products.count == 0 %>
      <% else %>
        <% @products.each do |product| %>
          <tr>
            <td id="addFood"><%= product.product_name %></td>   
            <td id="addFood"><%= product.product_code %></td>
            <td><input type="text" value=""  /></br></td> 
            <td><input type="submit" value="Ajouter" onClick="addToFood();"> </td>
          </tr> 
        <% end %>
      <% end %>
    </table>
    <%= will_paginate @products%>
    <!-- The list of food is displayed in the following div -->    
    <div id="foods"></div>
    &#13;
    &#13;
    &#13;

    我该怎么做?请帮我。

1 个答案:

答案 0 :(得分:0)

您需要发出ajax请求才能从应用服务器获取产品。如果你不熟悉ajax / rails,那么一个好的起点就是导轨指南http://guides.rubyonrails.org/working_with_javascript_in_rails.html