2 Oct 2010, 11:34pm
javascript Ruby on Rails: javascript link_to_function partial prototype replace_html
by bseanvt

leave a comment
javascript Ruby on Rails: javascript link_to_function partial prototype replace_html
by bseanvt
leave a comment
Execute Javascript When Using Link_to_function To Include a Partial in Rails
If you use the link_to_function to replace content in a div with content from a partial, any javascript that you include in the partial will not be executed. It is instead included, but will do nothing. Obviously, this isn’t the desired behavior. Why would we be taking the trouble to write the javascript in the partial? There is an easy fix. Instead of writing out the script tags, instead use the javascript_tag method to wrap whatever javascript you would like executed when the partial is loaded.
<%=link_to_function "say hello" {|p| p.replace_html "container", :partial => "say_hello" }%>
And now in my say_hello.erb file
<% javascript_tag do %>
alert("Hello World");
<% end %>
Render Partial if File Exists
If you ever want to render a partial but don’t want an error thrown you can either check for the existence of the file first
<%= render :partial => params[:controller]+"/sidebar" if File.exists?(RAILS_ROOT+"/app/views/"+params[:controller]+"/_sidebar.html.erb") %>
or you can catch the error that Rails throws
<%= render :partial => params[:controller]+"/sidebar" rescue nil %>


