【发布时间】:2015-11-29 19:07:41
【问题描述】:
在我的控制器中,我有这个方法可以返回特定书籍控制器/books_controller 的列表
def postings
@books = Book.postings(current_user.id).order("created_at ASC")
render :partial =>'postings'
end
我在views/books/_postings.html.erb中有一个部分
<div class="container">
<h4>My Partial Postings</h4>
<% @books.each do |book| %>
<div class="row">
<div class="col-sm-2"><img src="<%= book.image_path %>" alt="..." class="img-responsive"/></div>
<div class="col-sm-10">
<h4 class="nomargin"><%= book.title %></h4>
<p><%= book.description %></p>
<p>Quantity: <%= book.quantity %></p>
<p>Available for: <%= book.sale_type %></p>
</div>
</div>
<hr>
<% end %>
</div>
在我的路线中:
resources :books do
collection do
get 'postings'
end
end
关于运行 rake 路线:
postings_books GET /books/postings(.:format) books#postings
当我使用 localhost:3000/books/postings 时,我会得到所需的部分显示书籍列表。但是当我想从其他视图调用此部分时,例如从 localhost:3000/dashboard/index:
<div class="tab-pane" id="postings">
<%= render 'books/postings', :collection => @books %>
</div>
我收到以下错误:
Showing /home/swati/867/WorkSpace2/assignment_3/app/views/books/_postings.html.erb where line #4 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #4):
<div class="container">
<h4>My Partial Postings</h4>
<% @books.each do |book| %>
<div class="row">
<div class="col-sm-2"><img src="<%= book.image_path %>" alt="..." class="img-responsive"/></div>
<div class="col-sm-10">
我知道 render 只是渲染部分内容,而不在 books_controller 中调用我的方法发布,并且我的部分内容无法访问 @books ,这是 nil。这怎么可能?
【问题讨论】:
标签: ruby-on-rails ajax partials