Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveAdmin -- How to access instance variables from partials?

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 %>
like image 883
Hopstream Avatar asked Nov 09 '11 14:11

Hopstream


1 Answers

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").

like image 76
halfdan Avatar answered Oct 06 '22 01:10

halfdan