Reputation: 265
I have a simple Rails app which has an index page that shows 59 posts.
The problem is that if I search for something, Post.count continue to show me the original number of Posts on the index page - for example if I search for a post called 'Quilon', I get a search result showing just 1 post, but the Post.count still shows the original post number which is 59.
How do I fix this?
INDEX.HTML.ERB CODE
<%= Post.count %>
SEARCH FUNCTION IN POSTS CONTROLLER
def index
@posts = Post.all
if params[:search]
@posts = @posts.search(params[:search]).order("created_at DESC")
end
if params[:zagat_status].present?
@posts = @posts.zagat_status(params[:zagat_status]).order("created_at DESC")
end
end
Upvotes: 1
Views: 167
Reputation: 33542
You should give <%= @posts.count %>
instead of <%= Post.count %>
. <%= Post.count %>
returns count
of all the records. It is just same as
select count(*) from "posts"
so the conditions are ignored.
Upvotes: 1
Reputation: 52357
In your index action you narrow down the posts using some conditions, so you should operate on @posts
variable, not on the model Post
itself.
Which means you want to use @posts.count
.
Upvotes: 2