如何在Rails中使用带有嵌套资源的will_paginate?

3 ruby-on-rails nested-resources will-paginate

我是Rails的新手,我在使用set_paginate处理嵌套资源方面遇到了很大的麻烦.

我有两个模型,声明和发票.will_paginate正在处理Statement,但我无法让它在Invoice上工作.我知道我会做些傻事,但我无法弄明白,我在谷歌上找到的例子对我不起作用.

statement.rb
class Statement < ActiveRecord::Base
  has_many :invoices

  def self.search(search, page)
    paginate :per_page => 19, :page => page,
      :conditions => ['company like ?', "%#{search}%"],
      :order => 'date_due DESC, company, supplier'
  end
end

statements_controller.rb  <irrelevant code clipped for readability>
def index #taken from the RAILSCAST 51, will_paginate podcast
  @statements = Statement.search(params[:search], params[:page])
end

I call this in the view like so, and it works:
  <%= will_paginate @statements %>
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何让它适用于发票:

invoice.rb
class Invoice < ActiveRecord::Base
  belongs_to :statement

   def self.search(search, page)
     paginate :per_page => 19, :page => page,
       :conditions => ['company like ?', "%#{search}%"],
       :order => 'employee'
  end
end

invoices_controller.rb
class InvoicesController < ApplicationController

  before_filter :find_statement


  #TODO I can't get will_paginate to work w a nested resource
  def index #taken from the RAILSCAST 51, will_paginate podcast
        @invoices = Invoice.search(params[:search], params[:page])
  end

 def find_statement
    @statement_id = params[:statement_id]
    return(redirect_to(statements_url)) unless @statement_id
    @statement = Statement.find(@statement_id)
  end
end
Run Code Online (Sandbox Code Playgroud)

我试着这样称呼:<%= will_paginate(@invoices)%>

我玩这个时最常见的错误信息是:"@statements变量似乎是空的.你忘了传递will_paginate的集合对象吗?"

我不知道问题是什么,或者如何解决它.感谢您的帮助和指导!

小智 5

解决了 -

我将发票分页移动到Statement的控制器中,如下所示:

def show
  @statement = Statement.find(params[:id])

  #TODO move the :per_page stuff out to a constant
  @invoices = @statement.invoices.paginate :per_page => 10,
    :page => params[:page],
    :order => 'created_at DESC'


 respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => @statement }
 end
end
Run Code Online (Sandbox Code Playgroud)

并在这样的视图中调用它(为了可读性而修剪代码>

  <div id="pagination">
  <%= will_paginate @invoices %>
  </div>
  <table>
  <%# @statement.invoices.each do |invoice| -
  shows all invoices with no pagination,
  use @invoices instead%>
  <%
  @invoices.each do |invoice|
  %>
Run Code Online (Sandbox Code Playgroud)