我是Rails的新手,我在使用嵌套资源处理will_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 %>
但我无法弄清楚如何让它适用于发票:
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
我试着这样称呼它: &lt;%= will_paginate(@invoices)%&gt;
我玩这个时最常见的错误信息是: “@statements变量似乎是空的。你忘了传递will_paginate的集合对象吗?”
我不知道问题是什么,或者如何修复它。感谢您的帮助和指导!
答案 0 :(得分: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
并在此视图中调用它(为了便于阅读而修改代码&gt;
<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|
%>