【问题标题】:Default action performed by jQuery on the partial data in ruby on railsjQuery 对 ruby​​ on rails 中的部分数据执行的默认操作
【发布时间】:2012-11-30 22:52:53
【问题描述】:

我正在尝试以下操作。 主窗体中的客户选择选项。当用户在主窗体中选择客户时,他的帐单应该出现在所有后续部分中。

我正在使用 ryan bates 的 nested_form gem 来获取部分。代码如下。

<%= simple_nested_form_for @money_receipt do |f| %>

    <div class="customers"><%= f.collection_select :customer_id, Customer.all, :id, :name, options ={:prompt => "-Select a Customer"}, :style=>'width:210px;'%></div><br />
    /*rest of the code*/

    <%= f.link_to_add "Add line items", :money_receipt_line_items %>

内部部分

<div class="bill">
<%= f.collection_select :customer_bill_id, CustomerBill.all,:id,:id, {:prompt => "Select Customer bill"}, :style => 'width:202px;' %></div><br />

/*rest of the code*/

上面的jQuery代码如下

jQuery(document).ready(function(){
   jQuery(".customers select").bind("change", function() {
      var data = {
        customer_id: jQuery(this).val()  
      }
      jQuery.getJSON(
         "/money_receipts/get_bills",
        data, function(data){
      var result = "",a,x;
      var b = "<option>Select customer Bill</option>"
      for(i=0;i<data.length; i++)
      {
       a = data[i];
       result = result + "<option value="+a[0]+">"+a[0]+"</option>";
       console.log(result);
      }
     child=jQuery('.bill select').html(b+result);
    });
    });
  });

最后在我拥有的控制器中。 def get_bills

    @bill_amount = CustomerBill.find_all_by_customer_id(params[:customer_id]).map{|bill| [bill.id]} if params[:customer_id]
    respond_to do |format|
      format.json { render json: @bill_amount }
    end
  end

我试图过滤账单并放入 div id bill。现在,如果我在 jQuery 代码中执行 console.log,我将获得 customer_id 和账单,但我无法发布它。如果我在child 上执行console.log,我会得到jQuery() 的输出。我哪里错了?有没有更好的方法来实现上述目标?需要指导。提前致谢。

【问题讨论】:

    标签: jquery ruby-on-rails ruby-on-rails-3.2 nested-forms getjson


    【解决方案1】:

    我个人更喜欢将 HTML 放入部分而不是用 JS 代码绘制它的方式。

    像这样:

    money_receipt.js:

    $('.customers select').change(function(){
      $.getScript('/money_receipts/get_bills?customer_id='+$(this).val())
    })
    

    get_bills.js.erb:

    $('.bill select').html('<%=j render 'get_bills'%>')
    

    _get_bills.html.erb:

    <% @bills.each do |bill| %>
    <option value="<%=bill.id%>"><%=bill.title%></option>
    <% end %>
    

    代码行数越少,出错的地方就越少。

    【讨论】:

    • 谢谢,这很好:) 但是如何将上述方法应用于嵌套表单?如果我错了,请纠正我,我相信这仅适用于一个部分。
    猜你喜欢
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多