Ruby-on-rails – ActiveAdmin — How to access instance variables from partials

activeadminruby-on-railsruby-on-rails-3ruby-on-rails-3.1

I can't seem to access instance objects in partials. Example:

In controller I have:

ActiveAdmin.register Store do
  sidebar "Aliases", :only => :edit do
    @aliases = Alias.where("store_id = ?", params[:id])
    render :partial => "store_aliases"
  end
end

Then in the _store_aliases.html.erb partial I have:

<% @aliases.each do |alias| %>
  <li><%= alias.name %></li>
<% end %>

This doesn't work. The only thing that does work (which is horrible to do as I'm putting logic in a view is this:

  <% @aliases = Alias.where("store_id = ?", params[:id]) %> 
  <% @aliases.each do |alias| %>
     <li><%= alias.name %></li>
  <% end %>

Best Answer

When rendering a partial you need to actively define the variables that are given to that partial. Change your line

render :partial => "store_aliases"

to

render :partial => "store_aliases", :locals => {:aliases => @aliases }

Inside your partial the variables is then accessible as a local variable (not an instance variable!). You need to adjust your logic inside the partial by removing the @.

<% aliases.each do |alias| %>
  <li><%= alias.name %></li>
<% end %>

For further reading have a look at the API documentation (specifically the section "3.3.4 Passing Local Variables").

Related Topic