How to use will_paginate with a nested resource in Rails?
Asked Answered
D

1

3

I'm new to Rails, and I'm having major trouble getting will_paginate to work with a nested resource.

I have two models, Statement and Invoice. will_paginate is working on Statement, but I can't get it to work on Invoice. I know I'd doing something silly, but I can't figure it out and the examples I've found on google won't work for me.

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

But I can't figure out how to get it to work for Invoices:

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

And I try to call it like this: <%= will_paginate (@invoices) %>

The most common error message, as I play with this, is: "The @statements variable appears to be empty. Did you forget to pass the collection object for will_paginate?"

I don't have a clue what the problem is, or how to fix it. Thanks for any help and guidance!

Dachshund answered 23/9, 2009 at 13:18 Comment(0)
D
5

Solved -

I moved the invoices pagination into Statement's controller, like this:

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

and call it in the view like this (code trimmed for readability>

  <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|
  %>
Dachshund answered 25/9, 2009 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.