Jaycreation
Jaycreation

Reputation: 2089

ROR Access module function in a scope into a module

I try to create a module to manage access depending of an entity field on several models. The name of my entity field depends on the schema of the current model which call it.

My Module is :

 module Modules::EntityManagement
        extend ActiveSupport::Concern

        def entity_field_name
            self.class.connection.schema_search_path.split(",").first == 'public' ? 'entity_id' : 'entity_id__c'
        end


        included do
            scope :myscope, lambda {
                where('WHERE ? = ?', self.entity_field_name, 1) 
            }
        end
    end

When I call this on any model Mymodel.myscope

It returns an error

undefined method `entity_field_name' for #<Class:0x007ff62da60150>

I tried a lot of different syntax, but nothing works.

How can I use a dynamic field name based on database schema in a module's scope ?

Upvotes: 1

Views: 56

Answers (1)

apneadiving
apneadiving

Reputation: 115531

You have to wrap entity_field_name so it is a class method:

class_methods do
  def entity_field_name
    self.connection.schema_search_path.split(",").first == 'public' ? 'entity_id' : 'entity_id__c'
  end
end

If you also need at the instance level, add:

def entity_field_name
  self.class.entity_field_name
end

Upvotes: 1

Related Questions