Calling a jquery rails function?

advertisements

is it somehow possible to call a rails function or to access a rails object from within jQuery? I'd like to do something like:

jQuery(document).ready(function($) {
$('#mydiv').html("<%= @object.name %>");
});

OR

jQuery(document).ready(function($) {
$('#mydiv').html("<%= render :partial => "contacts" %>");
});

At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge.

Regards,

Sebastian


You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view

<script type="text/javascript">
<%= yield :footerjs %>
</script>

and in the view do something like:

<% content_for :footerjs do %>
jQuery(document).ready(function($) {
$('#mydiv').html('<%= escape_javascript(render :partial => "contacts") %>');
});
<% end %>

You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.