Partial Rails3.x rendering + coffeescript

I have the following requirement. I have a "school" and as a last option I am adding a new school, so if the user selects this option, I want to load the new_school form as 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 the prototype that I used for this

 Ajax.Updater (aka Rails link_to_remote :update => 'some_div') 

and rails> 3 + jQuery I am familiar with *.js.erb and have something like

 $("#school_form").html("<%= escape_javascript(render(:partial => "form"))%>"); 

But I'm new to coffeescript , and I have no idea how to do this using coffeescript , can someone help me :) (because I believe that you do not need to make a server request for this)

So far I have done the 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]) 
+4
source share
2 answers

Use a hidden div.

In general, you do not want to try to mix JS and HTML. Acceleration can be complex, error prone, and inconvenient due to cross-site scripting attacks.

Just draw your form in a div, which is 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 a slide or fading. This gives your application a more streamlined feel.

No need for AJAX. This pattern is so common that I have the style of the entire application program defined as follows.

 .not-displayed { display: none; } 

Then, using HAML (if you're at it), the HTML template will be simple:

 #school_name_form.not-displayed = render 'form' 
+4
source

You can try to display the form partially inside the hidden div (not too correct from the semantic point of view) or put the html form as the data attribute of any corresponding element, something like

 f.select school_name, ... , data: {form: escape_javascript(render(:partial => "form"))} 

And coffeescript

 $ -> $('#school_name_select').change -> unless $(this).val() $('school_name').html($('#school_name_select').data('form')) 
+2
source

All Articles