ActiveAdmin — How to access instance variables fro

2020-07-06 09:02发布

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 %>

2条回答
SAY GOODBYE
2楼-- · 2020-07-06 09:47

You have to pass your instance variable to your partial in order to use it there:

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

Then in your partial you will be able to use it as local variable

<% aliases.each do |alias| %>
  <li><%= alias.name %></li>
<% end %>
查看更多
姐就是有狂的资本
3楼-- · 2020-07-06 09:49

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

查看更多
登录 后发表回答