title: How to use an instance method in a where clause
body: <p>In my <code>Category</code> model I have an instance method that adds up all the price averages for all products within a category:</p>
  
  <pre><code>def price_average(store_id)
    products.pluck(:price_average).map { |h| h[store_id] }.sum
  end
  </code></pre>
  
  <p>In my <code>Category</code> controller I am trying to use a filter to only show categories where the <code>price_average</code> is above a specific amount. How can I do this?</p>
  
  <p>My main challenge here is that <code>price_average</code> is not a column name so doing something like <code>@categories.where("price_average('1') &gt; 1000")</code> just fails. </p>
  
  <p>The structure of the models goes something like this:</p>
  
  <pre><code>class Category &lt; ApplicationRecord
      # t.string "name"
      # t.datetime "created_at", precision: 6, null: false
      # t.datetime "updated_at", precision: 6, null: false
  
      has_and_belongs_to_many :products
      has_many :prices, through: :products
  
      def price_average(store_id)
        products.pluck(:price_average).map { |h| h[store_id] }.sum
      end
  end
  
  
  class Product &lt; ApplicationRecord
      # t.string "name"
      # t.datetime "created_at", precision: 6, null: false
      # t.datetime "updated_at", precision: 6, null: false
      # t.jsonb "price_average", default: {}
  
      has_and_belongs_to_many :categories
      has_many :prices
  
  end
  </code></pre>
  
  <p>In the <code>price_average</code> column I'm storing json where store_id is the index used to retrieve the value.</p>