0

  def index
     tag_array=[]
     courses = current_user.studio.courses
     courses.each do |a|
         tag_array << a.age_tag.id
         tag_array << a.level.id
         tag_array << a.category.id
      end
      @tags=current_user.studio.tags
      tags.each do |d|
        e=tag_array.where(:id => d).count
          d.store("count",e);
      end
          
  end

I'm looking for a way in rails to count the number of times the key/value pair of :id => d shows up in an array, then append it to a value in an each statement. Rails keeps throwing errors saying that .where and .store are not valid functions.

2 Answers2

0

.where is an activerecord array method and not simple array method.. In your case, you can..

def index
  tag_array = current_user.studio.courses(:age_tag, :level, :category).map do |a|
    [a.age_tag.id, a.level.id, a.category.id]
  end.flatten
  count_hash = current_user.studio.tags.map do |t|
    ["count_#{t}", tag_array.count(t)]
  end.to_h
end
Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36
0

You should be able to pluck the columns with:

Studio.left_joins(courses: [:age_tag, :tags, :level, :category])
      .where(id: current_user.studio)
      .pluck('age_tags.id, levels.id, categories.id, COUNT(tags.*)')

.left_joins is new in Rails 5. See LEFT OUTER JOIN in Rails 4 for Rails 4.

max
  • 96,212
  • 14
  • 104
  • 165