Search code examples
jqueryruby-on-railsajaxmodelcollection-select

Populate textfields on new form from another model's existing records on select rails


I have a DefaultTemplate model with existing records in it. I have another Template model where i have a collection_select with DefaultTemplate's Records.

What i want to do is that as soon as user selects one of these options, its associated data such as the content and type should be automatically populated in the text_fields of the New Form of Template so they can be saved.

I have researched and found that i can do this with JQuery and Ajax Calls, however i'm clueless about where to start? I referred Auto populate text_fields based on selected item from another collection_select in Rails 3 and it answers what i want but the person himself finds the code horrible. I'll be grateful for any help. Thanx


Solution

  • SOLVED!!

    ok, so after scratching my head for 2 days, i found that the answer was rather simple. Only i have been too afraid to even give ajax a try that i never really paid much attention to it. Just in case some one is looking for the same thing, here is the solution that worked for me.

    application.js file

    $(function($) {
        $("#email_template_id").change(function() {
            var selected_id = $("#email_template_id").val()
            if (selected_id == '')
            {
              $('#email_template_email_subject').val('')
            }
            else {
              $.ajax({
                type: "GET",
                url: "/default_email_templates/" + selected_id + ".json",
                dataType: 'json',
                success: function(data){
                  $('#email_template_email_subject').val(data.email_subject)
                }
              });
            }
        });
    });
    

    View (In _form.html.erb of the EmailTemplate where the DefaultEmailTemplate is the Model whose values should be appearing on selection )

    <%= form_for(@email_template) do |f| %>
       <div class="field">
         <%= f.label :default_email_template_id, "Template Type" %>
         <%= f.collection_select(:id, DefaultEmailTemplate.all, :id, :email_type, {prompt: "Select one"}, {:data => {remote: true}}) %>
       </div>
       <div class="field">
         <%= f.label :email_subject %>
         <%= f.text_field :email_subject %>
       </div>
       <div class="actions">
        <%= f.submit %>
       </div>
     <% end %>
    

    We can reduce the ajax code by simply passing parameters one after the other but, i'm not well aware of that and dint really try that yet. Please post any suggestions about the code. Thanx.

    P.S: Maybe i wasn't looking properly but when i did, these helped me a lot

    How to do an Ajax GET request to get data from rails and pass it to javascript(google maps)?

    passing text_field values in ajx on rails