3

我是 Rails 的新手,在让 will_paginate 使用嵌套资源时遇到了很大的麻烦。

我有两个模型,Statement 和 Invoice。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 %>

但我不知道如何让它为发票工作:

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

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

最常见的错误消息是:“@statements 变量似乎为空。您是否忘记传递 will_paginate 的集合对象?”

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

4

1 回答 1

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

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

  <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|
  %>
于 2009-09-25T07:13:18.637 回答