9

I am attempting the following. A customer select option in the main form. when a user selects a customer in the main form his bills should appear in the all the subsequent partials.

I am using ryan bates's nested_form gem to get the partial. the code is as follows.

<%= 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 %>

inside the partial

<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*/

the jQuery code for the above is as follows

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);
    });
    });
  });

and finally in the controller i have. 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

i was attempting to filter the bills and put in the div id bill. Now if i do a console.log in jQuery code i am getting the customer_id and the bills but i am not able to post it. if i do console.log on the child i get output as this jQuery(). where am i going wrong? is there a better way to achieve the above? guidance required. Thanks in advance.

deeraj
  • 148
  • 11

1 Answers1

7

I personally prefer the way of putting HTML into partials instead of drawing it with JS code.

Like this:

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 %>

With fewer lines of code there are less places for errors to creep in.

  • Thank you, this is great :) but how to apply the above method for a nested form? correct me if i am wrong i believe this apply s to just one partial. – deeraj Dec 19 '12 at 06:38