0

私はこのカスタムモデルを持っており、いくつかのメソッドが含まれています:

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
4

1 に答える 1

0

サブクラスで使用されるテーブル名を呼び出したい場合は、完了です - それは既に行われています:

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
于 2012-09-14T15:11:59.857 に答える