ActiveAdmin — How to access instance variables from partials?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-09 15:55:08

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/8066605/activeadmin-how-to-access-instance-variables-from-partials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!