0

データベースから 2 つのテーブルを削除しようとしています。テーブルは message_sort_options と per_page_options です。これらのテーブルには基本的に、ユーザーが設定テーブルで設定として設定できるオプションである 5 つのレコードしかありません。プリファレンス テーブルには、sort_preferences や per_page_preference などの列があり、どちらもオプションを含む他の 2 つのテーブルのレコードを指しています。オプションの仮想属性と固定値を使用してモデルを設定するにはどうすればよいですか? 設定が検索されるたびにテーブル検索が不要になりますか?

4

2 に答える 2

0

これを試して:

class MessageSortOption

  def self.get_cached_option(id)
    # store the hash of the options in a class variable
    (@@option_cache ||= Hash[ *all.collect{|o| [o.id, o]}.flatten])[id]
  end

end

class PerPageOption

  def self.get_cached_option(id)
    # store the hash of the options in a class variable
    (@@option_cache ||= Hash[ *all.collect{|o| [o.id, o]}.flatten])[id]
  end
end

class User
  has_one :preference
end


class Preference

  def sort_preference
    MessageSortOption.get_cached_option(attributes['sort_preference'])
  end

  def per_page_preference
    PerPageOption.get_cached_option(attributes['per_page_preference'])
  end

end

これで、次のように設定にアクセスできます。

current_user.preference.sort_preference
current_user.preference.per_page_preference
于 2010-03-25T20:44:02.907 に答える
0

app_config.ymlディレクトリにファイルを作成しますconfig

page:
  small: 10
  medium: 20
  large: 30


sort:
  name: name DESC  
  amount: amount ASC
  date: created_at DESC  

UserOptionsmodels ディレクトリにクラスを作成します。

class UserOptions
  def self.page_option key
    options['page'][key] rescue nil  
  end

  def self.sort_option key
    options['sort'][key] rescue nil
  end

  def self.options
    @options ||=  YAML.load_file( File.join(RAILS_ROOT, 
                    "config", "app_config.yml")) rescue {}
  end


  # use this in the view to set the preference
  def self.page_collection
    option_collection 'page'
  end

  # use this in the view to set the preference
  def self.sort_collection
    option_collection 'sort'
  end

  def self.option_collection key
    (options[key]|| {}).to_a
  end
end

モデルを構成します。

class User
  has_one :preference
end

class Preference

  def sort_preference(default = nil)
    UserOptions.sort_option(attributes['sort_preference']) || default
  end

  def per_page_preference(default = nil)
    UserOptions.page_option(attributes['per_page_preference']) || default
  end

end

これで、次のことができます。

current_user.preference.per_page_preference

# use 10 as the page size if no value is given
current_user.preference.per_page_preference(10)
于 2010-03-25T22:48:04.387 に答える