Thursday, February 17, 2011

How to keep track of information over several calls to render :partial

I am using attribute_fu to render a nice block of rows for a particular table.

<%= f.render_associated_form(@foo.bars, :new => 5) %>

I would like to have the bar partial have some notion of a bit of state. (Because the notion is specific to the view, I do not want to externalize this to the Bar model itself and calculate it in the controller.) For simplicity's sake, pretend it is the index of the bar in the @foo.bars list.

(I am aware that if this was the case I could use the :collection => @foo.bars to enable bar_counter... this doesn't appear to function in my tests but I have seen docs for it.)

My question -- how do I pass a variable into the partial such that I can keep and edit the state? Naively, I assumed that doing something like

<% @tmp = {:index => 1} %>
%= f.render_associated_form(@foo.bars, :new => 5, :locals => {:tmp => @tmp}) %>

#goes in the view
<%= tmp[:index] += 1 %>

would work. tmp gets passed appropriately but calling [] throws "Uh oh, you just called a method on nil". Surprisingly to me, I can do tmp.inspect, tmp.class, etc to look at the Hash, and these have the results I would expect. But tmp[:index] or tmp[:anything_I_want] cause it to blow up.

Making tmp an array had similar results.

Any ideas?

From stackoverflow
  • I ended up solving this in a thoroughly Rails fashion -- patching :attribute_fu to meet my needs. Hopefully I'll be able to release my patches to the community fairly soon.

  • The behavior you describe above seems like it must be a bug in attribute_fu, since the local isn't getting properly passed along, which it definitely should. I'd be interested to know what you did to patch it.

0 comments:

Post a Comment