Archive for the ‘rails’ category

Hidden counter in partial collections

February 4th, 2008

A quick tech post to share knowledge:

If you need a counter, iterator, index, loop variable number type thing inside a partial rendering a collection then you can simply use an undocumented counter called [partialname]_counter.

render :partial => 'parrot', :collection => @parrots

Then in _parrot.html.erb you can use:

parrot_counter

I like this like I like each_with_index. :)

Rails2 foot note: I think the :collection option can be dropped in my example with the names I’ve used here but I’ve left it in for clarity.

observe_form values lost in the ether

September 21st, 2007

When using observe_form, there’s a sneaky nastyness. (Rails 1.2.3) It’s a bit inconsistent. Hopefully this will clear it up.

With no ‘update’ or ‘with’ parameter then the values aren’t passed:
new Form.Observer('theform', 1, function(element, value) {new Ajax.Request('/controller/action', {asynchronous:true, evalScripts:true})})

Surely this is a bug? It should include ‘parameters:value’.

Using – :with => ‘values’
new Form.Observer('theform', 1, function(element, value) {new Ajax.Request('/controller/action', {asynchronous:true, evalScripts:true, parameters:'values=' + value})})

Getting there but still doesn’t quite work. Try it and you’ll see why.

Using – :update => {}, and no ‘with’
new Form.Observer('theform', 1, function(element, value) {new Ajax.Updater({}, '/controller/action', {asynchronous:true, evalScripts:true, parameters:value})})

This now works as it’s changed to use the Ajax.Updater passing the parameters as we wanted in the first attempt.
I hope his saves someone some time :-)

Credits due here for the empty hash fix: http://wiki.rubyonrails.org/rails/pages/observe_form+-+Passing+Parameters