ActiveAdmin-如何从局部访问实例变量? [英] ActiveAdmin -- How to access instance variables from partials?
问题描述
我似乎无法局部访问实例对象。示例:
I can't seem to access instance objects in partials. Example:
在控制器中,我有:
ActiveAdmin.register Store do
sidebar "Aliases", :only => :edit do
@aliases = Alias.where("store_id = ?", params[:id])
render :partial => "store_aliases"
end
end
然后在_store_aliases.html.erb中部分我有:
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 %>
推荐答案
渲染部分时,您需要主动定义提供给该部分的变量。更改行
When rendering a partial you need to actively define the variables that are given to that partial. Change your line
render :partial => "store_aliases"
至
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 %>
要进一步阅读,请参阅 API文档(特别是 3.3.4传递局部变量部分)。
For further reading have a look at the API documentation (specifically the section "3.3.4 Passing Local Variables").
这篇关于ActiveAdmin-如何从局部访问实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!