Reputation: 886
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
Upvotes: 1
Views: 1690
Reputation: 1784
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]
.
Upvotes: 0
Reputation: 2675
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>
Right approach
<p><%= category.articles.where(title: params[:q][:title_cont]).count %></p>
Upvotes: 0
Reputation: 7136
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 %>
Upvotes: 1