调用与部分轨道相关的方法

时间:2015-11-29 19:07:42

标签: ruby-on-rails ajax partials

在我的控制器中,我有这个方法,向我返回特定书籍控制器/ 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 / postss时,我得到了所需的部分书籍列表。但是当我想从其他视图中调用此部分时,例如来自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">

我知道渲染只是渲染局部而不调用books_controller中的方法贴子而我的局部无法访问@books,这是零。如何解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

当您访问dashboard/index时,您实际上正在调用index dashboards_controller方法。如果您想在那里呈现books/postings部分,则需要在该控制器中添加书籍列表(@books)。

此处有更多信息:http://guides.rubyonrails.org/action_controller_overview.html