【问题标题】:How to access a specified table in database through a custom model class, Ruby on Rails?如何通过自定义模型类Ruby on Rails访问数据库中的指定表?
【发布时间】:2012-09-14 14:39:38
【问题描述】:

我有这个自定义模型,其中包含一些方法:

class GenericModel < ActiveRecord::Base 
  self.abstract_class = true

  def get_settings
   .....
  end
end

我想在我的各种其他模型中继承这个 GenericModel 类,如下所示,以便我可以访问这些自定义方法:

class ProvinceSetting < GenericModel 
end

class CitySetting < GenericModel 
end

但是,如何编写我的自定义方法,以便它根据调用它的 Model 类对数据库中的特定表起作用?欢迎任何指点

这是 GenericModel 中 get_settings 的正确实现吗,其中 self 将引用适当的模型名称?

def self.get_settings(user_id)
    user_session = SettingsSession.find_by_user_id(user_id)

    if !user_session.blank?
      if setting_orig = self.find_by_settings_session_id(user_session.id)
          setting = setting_orig.dup
      end

    else
      setting = self.first.dup
    end 

 return setting
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 model


    【解决方案1】:

    如果你想调用子类使用的表名,那么你就完成了——它已经这样做了:

    class GenericModel < ActiveRecord::Base
      def get_settings
        all # this will get all settings for the subclass that calls it
      end
    end
    

    如果您需要使用其他表名,请在定义表名的每个子类中创建一个方法,并在抽象基础模型中调用该方法:

    class ProvinceSetting < GenericModel
      def special_table_name
        'foo'
      end
    end
    
    class CitySetting < GenericModel
      def special_table_name
        'bar'
      end
    end
    
    class GenericModel < ActiveRecord::Base
      def get_settings
        ... # use 'special_table_name' method in a query
      end
    end
    

    【讨论】:

    • 添加了一些关于 get_settings 的细节,这是正确的实现吗?
    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2013-11-27
    • 2014-10-20
    相关资源
    最近更新 更多