Appending a Rails Partial with jQuery


#1

Im not sure which group to post in, so i thought i’d try both. Any
Rails peeps that use jQuery? Im having a problem.

I have followed Ryan B. Screencast about inserting a partial with
jQuery and currently have it working in my app. What i really would
like is to keep all my code in my application.js file vs a bunch of
files all over my view folders.

This is what i have in my application.js

$(document).ready(function() {
$(’#add_option’).click(function() {
$(this).addPollOption();
});
});

jQuery.fn.addPollOption = function() {
$("#poll_options").append(’#{escape_javascript render(:partial =>
“topics/poll_option”, :object => TopicOption.new)}’);
};

i have tried it with the #{} and the <%= %> both give the same result.

Instead of getting the partial to populate the div, it simply adds the
text to the div below the 2 existing form fields.

#{escape_javascript render(:partial => “topics/poll_option”, :object
=> TopicOption.new)}

Any thoughts?


#2

application.js is a place to park your custom javascript routines.
Therefore, the document ready call that you have there does not make
sense:

$(document).ready(function() {
$(’#add_option’).click(function() {
$(this).addPollOption();
});

Put call in your “layout” file(s), e.g., application.html.erb for
example. You can even add it to the “erb” files where you need this
functionality.

Also, you need to follow Ryan’s screencast more closely. You will
notice that he has the javascript code to append the partial in
create.js.erb file. That is extremely important.

It is quite common to have Javascript “snippets” in various files and
have multiple document ready calls in place. It is a bit different
than what we are used to as Ruby or Ruby on Rails programmers but it
is best to get used to it. It is better than Obstrusive Javascript :slight_smile:


#3

I’ve not watched the screencast, but I would assume that if you’ve put
that code in application.js it’s not going to work.

the #{} and <%= %> tags are escapes for the code to be interpreted on
the server by ruby. application.js is interpreted on the client by
javascript. I suspect the code snippet needs to go between some

tags in a ruby template.

#4

It can also be handy to have a main document ready block in the layout
file:

<% javascript_tag do -%>
$(document.ready(function() {
<%= yield :document_ready %>
});
<% end -%>

Then you can drop page-specific JS into it with content_for. You’ll
also be in an ERB context, so you’ll have a lot more luck getting your
example above (using <%= %>) to work.

I find this a lot more straightforward than stuffing every bit of JS
into application.js, as it puts the code closer to the HTML it’s
designed to manipulate.

–Matt jones