Random Rails Notes
This page features random Ruby on Rails snibbets that I have come to rely upon for various goals.
link_to_function
Need to create a link that simply calls a javascript function? Here’s the way I do it:
link_to_function "Hello", "alert('hi')"
Simple enough, huh?
ActionMailer SSL
I was getting STARTTLS errors:
lost connection after STARTTLS
I added this to my ActionMailer configuration:
:openssl_verify_mode => 'none'
In another instance, I simply turned off tls in my Postfix configuration.
Sorting / Ordering ActiveRecord Results
Here’s a simple example for descending the order:
@memories = Memory.where(:user_id => @current_user.id).limit(25).find(:all, :order => "date DESC")
Render Partial to a String in Rails 3
Rails prior to 3 had the h and the html_safe helper functions. In Rails 3, achieving the goal of these functions is done differently, as it seems that Rails 3 makes everything “safe”. This is all well and good, but today when I tried to render a partial to a string within a helper function, then return the resulting string to a template for output, the HTML entities had already been escaped.
To avoid this, I searched for “rails 3 render scape” and found a post at StackOverflow. It explained the raw method, and suggested using it within the partial. That didn’t work for me, as I explained:
This helped me, thank you. In my case, I render the partial directly from another template, as well from a helper which is called by a different template. Also, my partial is a form, so I didn't want to call raw for every string output. It works!
I use this syntax when calling the helper:
<%= raw(link_to_add_group_or_alt(@user.id)) %>
xml:space=”preserve”
Thanks to XML Please:
<%= form.text_area(:profile, "xml:space" => "preserve") %>
For this XSL / XML note, see also:
and:
<xsl:template match="@xml:space" />
Override Attributes