2012-11-23 22 views
4

我想應用分頁到我的Rails應用程序使用Kaminari。我還將基於0​​的簡單搜索表單合併到一起。當我嘗試應用kaminari頁面和每種方法時,我得到錯誤「未定義的方法頁面」。以下是我正在使用的代碼。使用簡單搜索與Kaminari分頁寶石

posts_controller.rb

def index 
    @posts = Post.search(params[:search]).page(params[:page]).per(2) 
end 

post.rb

def self.search(search) 
    if search 
    find(:all, conditions: ['title || body LIKE ?', "%#{search}%"], order: "created_at DESC") 
    else 
    find(:all) 
    end 
end 

index.html.erb

<%= paginate @posts %> 

當我刪除分頁搜索工作正常。當我刪除搜索時,分頁工作正常。我似乎無法使用它們,並具有正確的代碼功能。請告知如果我的代碼中有某些東西是我錯過了,導致它不能正常工作。

回答

9

在你的情況下,你從搜索方法返回的數組對象不是ActiveRecord :: Relation對象。

find(:all, conditions: ...) # find method will return an array object. 

添加覆在你的控制器,

def index 
    @posts = Post.search(params[:search]) 
    if @posts.class == Array 
    @posts = Kaminari.paginate_array(@posts).page(params[:page]).per(10) 
    else 
    @posts = @posts.page(params[:page]).per(10) # if @posts is AR::Relation object 
    end 
end 

雷分頁與陣列https://github.com/amatsuda/kaminari#paginating-a-generic-array-object

ActiveRecord的:: Relation對象,結帳這個http://railscasts.com/episodes/239-activerecord-relation-walkthrough

+0

這做到了。感謝您的迴應。 – Aaron

+1

@Aaron那你能否接受我的回答? :) – Santosh

+0

如果有解釋,這將是一個更好的答案......「給一個男人一條魚,你喂他一天,教一個男人去釣魚,你一輩子喂他。」 – Agush