简体   繁体   中英

Ruby on Rails and how to render partial using json and jquery

Ruby on Rails newbie whose confused and frustrated :) I've spent over a day on this and think I've probably just confused myself.

Basically, I'm trying to render a partial in a view. Here's what I have specifically: A form with 2 basic fields: Category and SubCategory. SubCategory changes depending on what the user selected in Category. I'm using "JQuery" with the assets pipeline enabled. This part works:

 
    contact_infos.js.coffee

    jQuery(document).ready(->
        $("select#contact_info_category_id").change(->
          id_value_string = $(@).val()
          if id_value_string == ""
            # if the id is empty remove all the sub_selection options from being selectable     and do not do any ajax
            $("select#contact_info_subcategory_id option").remove()
            row = "" + "" + ""
            $(row).appendTo("select#contact_info_subcategory_id")
          else
            # Send the request and update sub category dropdown
            tmp = '/subcategories/for_categoryid/' + id_value_string + '.json'
          $.ajax(
            type: 'GET',
            dataType: 'json',
            url: tmp,
            timeout: 2000,
            error: (XMLHttpRequest, errorTextStatus, error) -> alert "Failed to submit : " + errorTextStatus + " ;" + error,
              success: (data) ->
                # Clear all options from sub category select
                $("select#contact_info_subcategory_id option").remove()
                # put in a empty default line
                row = "" + "" + ""
                $(row).appendTo("select#contact_info_subcategory_id")
                # Fill sub category select
                $.each(data, (i, j) ->
                  row = "" + j.name + ""
                  $(row).appendTo("select#contact_info_subcategory_id")
                )
          )
        )
      )
    

It generates a json response correctly.

When the form loads, in addition to Category and SubCategory, I also have 2 text fields - previous_value and current_value; however, if SubCategory == "Full" then I hide previous_value and current_value and need to insert a partial with new fields.

I'm having no problem hiding previous_value and current_value fields with JQuery works and looks like this (this is inserted into the code above):

$("select#contact_info_subcategory_id").change(->
    id_text_string = $("#contact_info_subcategory_id option:selected").text()
    if id_text_string == "Full"
      $('#contact_info_previous_value_id').hide()
      $('#contact_info_current_value_id').hide()
    else
      $('#contact_info_previous_value_id').show()
      $('#contact_info_current_value_id').show()
  )

I created a div called "test" in my form where I want to insert the new fields if SubCategory is "Full" and of course, inserting this line into the contact_infos.js.coffee doesn't work:

  $('#test').html('<%= escape_javascript render("contact_infos/_full_name_info") %>')

as all I get on the page is the string "<%= escape_javascript render("contact_infos/_full_name_info") %>"

I've tried the following but can't get any to work:
1. creating a new.json.erb file with the following code:

<% self.formats = ["html"] %>
      test = {
        "html":"<%= raw escape_javascript(render :partial =>     'contact_infos/full_name_info',
                    :content_type => 'text/html')} 
                %>"
      }

This json file never triggered. My controller has this line:

format.json { render json: @contact_info }

Is this the best way to do this? If yes, what can I try next?


2. I saw a posting yesterday (I can't find it now - was on another computer) about creating a javascript variable (I called it fullnamefield) in the application.html.erb layout file as well as adding the js variable to the new.html.erb view, which I did. I also added this line to the contacts_infos.js.coffee:

('#test').html(fullnamefield) 

and it worked!! EXCEPT that then when I went to any other area of the site, I got an error.
3. As a workaround, I thought about trying to change the json that my jquery produces to a js and then trying to trigger the new.js.erb. I ran into trouble trying to convert the ajax call. I could create "json" and also "text" dataTypes but not script (not sure why).

So... any ideas/help? I've really been searching and I'm frustrated enough that I'm considering just creating all the fields and hidings/showing them as needed from JQuery, which would be so simple to implement but is just wrong.

UPDATE: Attempt 4 (or is it 40?):

What you wrote got me thinking... I think I'm close but not there yet.

In my _form.html.erb, I added to the Subcategory field data-remote, data-url and data-type:

<div class="field">
      <%= f.label :category_id %>
      <br/>
      <%= collection_select(:contact_info, :category_id, Category.all, :id, :name, options ={:prompt => "--Select a Category--"}) %>
    </div>
    <div class="field">
      <%= f.label :subcategory_id %>
      <br/>
      <%= collection_select(:contact_info, :subcategory_id, Subcategory.find_all_by_category_id(@contact_info.category_id), :id, :name, options ={:prompt => "--Select a SubCategory"}, "data-remote" => true, "data-url" => "/contact_infos/get_full_fields", "data-type" => :json ) %>
    </div>

Then in the contact_infos_controller.rb I added:

def get_full_fields
    @full_name = FullName.new
    respond_to do |format|
      format.js
    end
  end

In my routes.rb I modified contact_infos by adding collection do...

    resources :contact_infos do
        collection do
          get 'get_full_fields'
        end
      end

I created contact_infos\\get_full_fields.js.erb:

var full_fields_form = $('<%= j(render(:partial => "contact_infos/full_name_info"))%>');
$('#test').html(full_fields_form);

Now when I test this in the browser with debugger and change SubCategory to "Full" I can see that it runs correctly (I think) in that I'm getting this back:

Request URL:http://localhost:3000/contact_infos/get_full_fields?contact_info%5Bsubcategory_id%5D=3 Request Method:GET Status Code:200 OK

The "Type" is showing up as "text/javascript." The Response tab is just showing the javascript code but nothing is happening/triggering. Even when I place just a

alert('hello');

in the js file nothing happens.

Any ideas why?

Why not do it the same way you get subcategory data? Create a view containing the partial (and corresponding controller action) and call it via ajax when you want to display that content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM