我正在使用mongoid并且在生成普通脚手架后没有添加任何代码。
我想在投资组合索引视图页面上呈现类别列表。
所以我呈现为部分。但是得到了如下错误..
NoMethodError in Portfs#index
Showing /Users/suri/Dev/action2/app/views/cats/_list.html.erb where line #1 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #1):
1: <% @cats.each do |cat| %>
2: <li><%= cat.name %></li>
3: <% end %>
查看/ PORTF / index.html.erb
<div class="row">
<div class="span9">
<div class="row">
<ul class="thumbnails">
<% @portfs.each do |portf| %>
<li class="span3"style="border:1px solid black;">
<div class="thumbnail">
<% portf.images.each do |image| %>
<%= image_tag image.file.url(:small) %>
<% end %>
<div class="caption">
<h3><%= link_to (truncate portf.title, :length =>10), portf %></h3>
<p><%= truncate portf.decs, :length => 30 %></p>
<p><%= link_to 'Edit', edit_portf_path(portf) %>
<%= link_to 'Destroy', portf, method: :delete, data: { confirm: 'Are you sure?' } %></p>
</div>
</div>
</li>
<% end %>
</ul>
</div>
</div>
<div class="span3">
<div class="modal fade" id="portf_modal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Welcom to <%= image_tag 'logo.png', :height => 12 %></h3>
</div>
<div class="modal-body">
<%= form_for :portf, :html => { :multipart => true } do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<%= f.label :Category %><br />
<%= collection_select(:portf, :category, Cat.all, :name, :name) %>
<div class="field">
<%= f.label :decs %><br />
<%= f.text_area :decs, :class => 'span5', :rows => 10 %>
</div>
</div>
<div class="modal-footer">
<%= f.submit '올리기', :class => 'btn btn-primary' %>
<a href="#" class="btn" data-dismiss="modal">닫기</a>
<% end %>
</div>
</div>
<form class="form-search">
<div class="input-append">
<input type="text" class="span2 search-query">
<button type="submit" class="btn">Search</button>
</div>
</form>
<p>category</p>
<% render 'cats/list', :action => "index", :controller => "cats" %>
<a href="#portf_modal" data-toggle="modal" class="btn btn-primary">포트폴리오 올리기</a>
</div>
</div>
查看/猫/ _list.html.erb
<% @cats.each do |cat| %>
<li><%= cat.name %></li>
<% end %>
答案 0 :(得分:0)
我认为你误解了render partials in a view和rendering in the controller context之间的区别。不幸的是,两种方法都具有相同的名称,但用例完全不同。当您render in the view时,正如您在index.html.erb模板底部所做的那样,您通常会渲染部分内容。 partial有点像HTML片段,可用于显示项目集合。在您的情况下,您需要将集合存储在控制器中的@cats
实例变量中,然后在视图中呈现部分:
在您的控制器中:
@cats = Cat.all # (or any other collection of cats)
在您看来:
<%= render :partial => 'cats/list' %>
答案 1 :(得分:0)
@cats是一个实例变量,它将根据MVC架构从您的控制器传递到View。像
这样的东西def index
@cats = Cat.all
end
你的view / portf / index.html.erb(只保留你调用部分的最后一个时钟)
<强> WRONG 强>
<p>category</p>
<% render 'cats/list', :action => "index", :controller => "cats" %>
从右强>
<p>category</p>
<%= render :partial => "list", :collection => @cats %>
纠正您的偏见
view / cats / _list.html.erb(我们没有迭代@cats循环,因为我们将本地传递为集合
<li><%= cat.name %></li>