'will_paginate undefined method `total_pages' for #<ActiveRecord::Relation
undefined method `total_pages' for #<ActiveRecord::Relation [#<Post id: 9, title: "Testing", created_at: "2022-03-13 06:23:49.233178000 +0000", updated_at: "2022-03-13 06:23:49.531991000 +0000", description: "Yes">]> Getting error in pagination, if I add the pagination the search doesnt work, to make the search work pagination should be removed. Can someone help me solve this please.
posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: %i[ show edit update destroy ]
# GET /posts or /posts.json
def index
@posts = Post.paginate(:per_page => 5, :page => params[:page])
end
def search
@posts = Post.search(params[:keyword])
@keyword = params[:keyword]
render "index"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Only allow a list of trusted parameters through.
def post_params
params.require(:post).permit(:title, :content, :description)
end
end
post.rb file
class Post < ApplicationRecord
has_rich_text :content
validates :content, length: { minimum: 10 }
validates :title, presence: true
def self.search(keyword)
where(["title like? ", "%#{keyword}%"])
end
end
index.html.erb file
<p style="color: green"><%= notice %></p>
<div class="search-form">
<%= form_with url: search_path, method: :get, local: true do |f| %>
<%= f.text_field :keyword, value: @keyword %>
<%= f.submit "Search" %>
<% end %>
</div>
<h1>Titles</h1>
<div id="posts">
<% @posts.each do |post| %>
<%= render post %>
<p>
<%= link_to "Show", post %><br>
<%= "Created at:" %><%= time_ago_in_words(post.created_at) %><%= " ago" %><br>
<%= time_ago_in_words(post.updated_at) %><%= " ago" %>
</p>
<% end %>
<%= will_paginate @posts %>
</div>
I am expecting for both search and pagination to work. When I search a title it should render all the titles from all the pages.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
