Tuesday, March 1, 2011

Partial not receiving all variables from :locals

In my controller I have:

- @items.each do |item|
  = render :partial => 'item', :locals => { :item => item, :draggable => true }

And in the item partial I have:

%span{:id => "item_#{item.id}", :class => 'item'}
  = item.name
  - if defined?(draggable)
    = draggable_element "item_#{item.id}", :revert => true

This is not working, however, because defined?(draggable) returns false. The draggable_element is never rendered.

I know that item is passed through :locals because the rest of the partial renders. If I change the partial to read:

- if defined?(item)
  = draggable_element "item_#{item.id}", :revert => true

Then the draggable_element is rendered.

Any idea why :draggable is not getting passed to the partial?

From stackoverflow
  • Use local_assigns[:draggable] instead of defined?(draggable).

    From the Rails API "Testing using defined? var will not work. This is an implementation restriction."

    huntca : defined?(var) actually worked for me in all other instances, but obviously is not the way to go! Thanks.
  • I've solved this problem in the past by throwing this into the top of the partial.

     <% draggable ||= nil %>
    

    That allows me to do

     <% if draggable %>
    

    So long as I don't try to make the distinction between draggable being nil and never being passed.

0 comments:

Post a Comment