Search code examples
ruby-on-rails-3named-scopespork

Scope staticly reference another model resulting table not found


I use in-memory database for testing. The schema is reloaded in every test.

Recently my rspec complains that a table is not found. The reason is that a scope is referencing another model at load time.

class Item
  scope :public, where(:store_id => Store.public_store_ids())

class Store
  def self.public_store_ids
    self.public.pluck(:id)

The problem is that, during the initializing when item model is loaded in the memory, the schema for store table has not been loaded yet, but my scope will try to query the public store ids, which results in the "table not found" error.

How can I make my item scope to evaluate dynamically at runtime? I didn't want to use join because it can slow down my query, but would it be my only way?


Solution

  • I realized that I can just make it a class method so it is evaluated at run time

    def self.public
      store_ids = BeautyStreet::Store.public_store_ids()
      where(:store_id => store_ids)
    end