【问题标题】:ROR Access module function in a scope into a moduleROR 在一个作用域中访问模块函数到一个模块中
【发布时间】:2018-02-27 14:11:42
【问题描述】:

我尝试创建一个模块来根据多个模型上的实体字段来管理访问。 我的实体字段的名称取决于调用它的当前模型的架构。

我的模块是:

 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

当我在任何模型上调用它时 Mymodel.myscope

返回错误

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

我尝试了很多不同的语法,但没有任何效果。

如何在模块范围内使用基于数据库架构的动态字段名称?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord scope rails-activerecord


    【解决方案1】:

    你必须包装 entity_field_name 所以它是一个类方法:

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

    如果您还需要在实例级别,请添加:

    def entity_field_name
      self.class.entity_field_name
    end
    

    【讨论】:

    • 太棒了。非常感谢您的快速回答。包装成 class_methods 确实完成了这项工作。
    • 出于好奇,为什么不使用delegate :entity_field_name, to: :class
    • 你绝对可以 :) 口味问题 ;)
    • 好的,我以为那里有一个棘手的部分或隐藏的功能,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多