Sortable Tables

Rails has a helper function called sortable_element that generates ajax code to allow you to sort lists by dragging and dropping elements. The function defaults to handle lists and if you want to sort tables you should take note of the :tag option.

<%= sortable_element 'my_list',
:url => { :action => "order" },       
:tag => 'tr' %>

This should allow you to sort tables and hopefully save you from a big headache.

Alphabar on Rails

I am working on this little project right now using Ruby on Rails and I ran into some trouble with the alphabar plugin. First, alphabar uses the with_scope method which, since Rails 2.0 I believe, has been protected, giving me some errors since I froze my Rails version. I was able to overcome this obstacle by using the send method instead. Just change the last part of the find method of the plugin from:

model.with_scope({:find => {:conditions => conditions}})
{model.find :all}

to:

model.send(:with_scope, {:find => {:conditions => conditions}})
{model.find :all}

After I finally got that to work the plugin was very useful, although the alphabar was limited to letters and blank which is useful if you don’t need numbers. To accomodate numbers just add this to the alphabar helper:

('0'..'9').to_a.each do |i|
slots << i
end

Theoretically it should work for any character but I haven’t tried it yet.

So there you have it. Hoepfully somebody having trouble with this plugin will find this post useful.

nl2br in RoR

I recently found out that line breaks are not recognized when displaying a large block of text on the view (e.g. a post body). In PHP this was handled by the nl2br method but I had no luck finding a similar function in RoR. So I did what any sane person would do, create one myself. I placed this method in our model to format a particular field but it seems a better choice to put it in a helper.

def nl2br(text)

return text.gsub(/\n/, ‘<br/>’)

end

And there you have it, your very own nl2br method. Either you just found something really useful or I just wasted 2 minutes of your time. If anyone has a better solution or if I missed a function for this let us know by dropping a comment.