如何使用will_paginate与Rails的一个嵌套的资源?(How to use will_p

2019-07-19 04:21发布

我是新来的Rails,和我有大麻烦will_paginate与嵌套资源工作。

我有两个型号,声明和发票。 will_paginate正在发言,但我不能让它在发票上工作。 我知道我最好做一些愚蠢的,但我无法弄清楚,我已经在谷歌找到的例子不会为我工作。

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?”

我没有一个线索是什么问题或如何解决它。 感谢您的帮助和指导!

Answer 1:

解决了 -

我把发票分页到声明的控制器,就像这样:

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|
  %>


文章来源: How to use will_paginate with a nested resource in Rails?