Auto populate text_fields based on selected item from another collection_select in Rails 3

后端 未结 1 1762
长情又很酷
长情又很酷 2021-01-15 10:27

Hello people

I\'m trying to figured this out, but I still can\'t do it.

I have a rails 3 app, I\'m working with invoices and payments. In the form for

相关标签:
1条回答
  • 2021-01-15 10:59

    What you are going to want to do is route an ajax call to a controller, which will respond with json containing the information. you will then use jquery to populate the different fields.

    In your routes:

    get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
    

    In your invoice_controller:

    def get_json
      invoice = Invoice.find(params[:invoice_id])
      render :text => invoice.to_json
    end
    

    In your invoice model (if the default to_json method is not sufficent):

    def to_json
      json = "{"
      json += "id:'#{self.id}'"
      json += ",date_created:'#{self.date}'"
      ...      //add other data  you want to have here later
      json += "}"
    end
    

    In your javascript file,

    $("#invoice_selecter").change(function(){  //calls this function when the selected value changes
      $.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){  //does ajax call to the invoice route we set up above
        data = eval(data);  //turn the response text into a javascript object
        $("#field_1").val(data.date_created);  //sets the value of the fields to the data returned
        ...
      });
    });
    

    You are probably going to run into a few issues, i would highly recommend downloading and installing fire bug if you are not on google chrome.. and if you are, make sure you are using the development tools. I believe you can open them up by right clicking and hitting inspect element. Through this, you should be able to monitor the ajax request, and whether or not it succeeded and things.

    0 讨论(0)
提交回复
热议问题