Rails - Make ajax request from javascript event and load partial
===

what's up?

I'm using rails 3.2.3 with ruby 1.9.2p290.

I have a model Purchase which has many purchase_payments:

    class Purchase < ActiveRecord::Base
      has_many :purchase_payments, :class_name => 'PurchasePayment', :dependent => :destroy
      accepts_nested_attributes_for :purchase_payments
      
      def Purchase.build_payments(count)
        #Creat #count payments with some logic for each of them
      end
    end

In my form, I have number_field:

    <td>
      <%= f.number_field :payments_count, :min => 0 %>
    </td>

Now, I'd like to have the purchase_payment fields appear based on the number of payments. For that, I have a specific div:

    <div id="purchase_payments_space"> </div>

Every resource I've found so far, talks about ajax generated by helper tags, like link_to ... , :remote => true, but using this tags, the user would have to click on the link to have the remote function called. In other part of my app, I use jquery ajax request and I'm trying to use like this for sending the request to my controller:

    function load_payments() {
      $.ajax({
        type: "POST",
        url: "/purchases/build_payments/" + document.getElementById("purchase_payments_count").value,
      });
    }

    $(document).ready(function() {
      $("#purchase_payments_count").change(load_payments);
    }

In my controller, I have the respond_to :js right after my class declaration and the following method:

    def build_payments
      pc = params[:payments_count].to_i
      @purchase = Purchase.new

      @purchase_payments = Purchase.build_payments pc

      respond_to do |format|
        format.js
      end
    end

This way I have my app/views/purchases/buid_payments.js.erb run ok.
The thing is, I'm building a collection of payments that should be included in my form, and doing things the way I'm currently doing doesn't look like rails would do this. This way I will have to write much code in the js.erb file and still I can't figure out how I'll make the create method build the complete purchase from the params (I don't know how to build the form from the javascript).

I looked at several different ways but none have given an integrated solution for making an ajax request from a javascript event and have the view create the nested fields for my nested attributes (its a collection of purchase_payment I must remember).

I saw http://railscasts.com/episodes/196-nested-model-form-part-1 and http://railscasts.com/episodes/197-nested-model-form-part-2 but those build on top of helper methods like link_to and link_to_function.

Can anyone point me how can I accomplish that?


