简体   繁体   中英

Ruby on rails: count the number of records per category after filtering

I have a Ransack search form on browse.html.erb which filters articles by title and category. When i first enter the browse page without doing any search, i want a list of all categories with the count of articles belonging to the category to be rendered on the sidebar. After I submit a search, i want the list of categories and article count to be updated based on the search results.

I am unable to understand why this error occurs:

undefined method `where' for #<Article:0x007f1e60f193e0>

browse.html.erb

  <% @categories.each do |category| %>
    <p><%= link_to category.name, browse_articles_path(category: category.name) %></p>
    <p><%= category.articles.select{|article| article.where(title == params[:q][:title_cont])}.count %></p>
  <% end %>

articles_controller.rb

  def browse
    @q = Article.ransack(params[:q])
    @articles = @q.result.includes(:categories, :users)
    if params[:q][:title_cont] == present?
      @categories = Category.joins(:articles).where('article.title LIKE ?', params[:q][:title_cont]).uniq
    else
      @categories = Category.includes(:articles).order('name ASC').all
    end
  end

In Rails where is an ActiveRecord method, a query interface for retrieving data from your database. In your example you'd have to do this instead:

<%= category.articles.where(title: params[:q][:title_cont]).count %>

Active Record Query Interface

Diana!

You are using select on articles array and pass article variable to a block. article variable contains just a plain Article. This object doesn't have .where method.

Rewrite:

category.articles.select{|article| article.where(title == params[:q][:title_cont])}.count

To:

category.articles.ransack(params[:q]).result.count

But this code is still can be refactored and improved a lot. Can you share a full view please?

Edited

category.articles.where(title: params[:q][:title_cont]).count

Is a bad solution, because it will check for articles with fully equal title, while you are looking for articles which title contains substring of params[:q][:title_cont] .

WHY?

You are trying to execute where condition on Article object,Not on Article relation.

Either replace

<p><%= category.articles.select{|article| article.where(title == params[:q][:title_cont])}.count %></p>

with

<p><%= category.articles.select{|article| article.class.where(title == params[:q][:title_cont])}.count %></p>

OR

Right approach

<p><%= category.articles.where(title: params[:q][:title_cont]).count %></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM