rendering a partial Rails3.x + coffeescript

coffeescript, jquery, ruby-on-rails-3

Solution

Use a hidden div.

In general, you don't want to bother trying to mix JS and HTML. The escaping can be complicated, error-prone, and flat out dangerous due to the possibility of cross-site scripting attacks.

Simply render your form partial in a div that's not displayed by default. In ERB:

<div id="school_name_form" style="display: none;">
  <%= render 'form' %>
</div>

In your CoffeeScript:

$ ->
  $('#school_name_select').change ->
    if $(this).val()
      $('#school_name_form').slideUp()
    else
      $('#school_name_form').slideDown()

I recommend using a small, tasteful transition like slide or fade. It gives your app a more polished feel.

No AJAX is required. This pattern is so common that I have an application-wide style defined as follows.

.not-displayed {
  display: none;
}

Then using HAML (if you're into that), the HTML template becomes simply:

#school_name_form.not-displayed
  = render 'form'

Problem

I have the following requirement. I have a 'school' drop down and as the last options I have add new school, so if the user selects that option I want to load the new_school form as a partial via ajax. I'm on ``` gem 'rails', '3.2.9' gem 'coffee-rails', '~> 3.2.1' Jquery via gem 'jquery-rails' ``` Earlier with rails < 3 and prototype I used to do it with ``` Ajax.Updater (aka Rails link_to_remote :update => 'some_div') ``` and with rails > 3 + JQuery I'm familiar with `*.js.erb`, and having something like ``` $("#school_form").html("<%= escape_javascript(render(:partial => "form"))%>"); ``` But I'm new to `coffeescript` and I have no idea on how to do this with `coffeescript`, can someone help me :), (because I believe you shouldn't have to do a server request for this) So far I have done following to catch the `select_tag` change event ``` $ -> $('#school_name_select').change -> unless $(this).val() $('school_name').html([I want to have the _new_school_form partial here]) ```

Original source