[英]How to use will_paginate with a nested resource in Rails?
我是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 %>
但我無法弄清楚如何讓它適用於發票:
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)%>
我玩這個時最常見的錯誤信息是:“@ state變量似乎是空的。你忘了傳遞will_paginate的集合對象嗎?”
我不知道問題是什么,或者如何解決它。 感謝您的幫助和指導!
解決了 -
我將發票分頁移動到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|
%>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.