Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ActiveRecord with key/value pair table

I have an existing table from a third-party database that I am hooking into that stores key/value pairs. Two columns, one for "param" and the other for "paramvalue". I need to access these stored values for a plugin app that I'm developing, and I'm trying to think of the best way to get the values into the easiest format to use throughout the application. What I had thought of was somehow constructing dynamic methods in the AR model that I could call based on the param name. Something like SysParams.base_url which would map to the record for [base_url,http://www.thesite.com]. Kind of like the built-in AR methods for things like Record.find_by_column_name

The ultimate question: is something like this possible? If so, is it a good idea? If so, how would one go about it?

like image 697
John Avatar asked Sep 13 '26 02:09

John


1 Answers

here's how I deal with such stuff, but this is only a good idea if the amount of keys is not too large.

1.Create a model to Access your DB like this one:

app/models/config_table.rb

class ConfigTable < ActiveRecord::Base
  # whatever you need here
end

2.Create an initializer

config/initializers/admin_config.rb

class AdminConfig
  # uncomment this if in development
  #unloadable

  # I assume you have the fields key/value in your 
  # ConfigTable you may need to change this

  def self.all
    # create a cached hash
    @cache ||= ConfigTable.all.inject({}) do |hsh, c_config|
      hsh[c_config.key.to_sym] = c_config.value
      hsh
    end
  end 

  def self.get(key)
    self.all[key.to_sym]
  end

  def self.[](key)
    self.all[key.to_sym]
  end
end

Usage examples (anywhere in your Appp):

AdminConfig.get(:hostname)
AdminConfig.get('hostname')
AdminConfig[:hostname]
AdminConfig['hostname']

If you need to reload your Configuration due to changes, you will have to restart all your running App instances. You may need to adapt the namings of the table/columns of course :)

If you need a solution for bigger sets of key/values, I recommend you to store it in the rail's cache and maybe use redis-store :)

Have fun

like image 86
sled Avatar answered Sep 16 '26 18:09

sled