views:

22

answers:

4

I'm trying to access a model for global system settings. It should be loaded in almost every controller. The problem is I can't find any help on getting rails to load the dam thing.

If this helps, the model is called Config and has two columns; 'key' and 'value'

I come from a background in PHP. I remember codeigniter could load models via.

$this->load->model('a_model_name');

The controllers I'm trying to load the model in do not have the same name as the model.

+1  A: 

Rails autoloads classes when it needs them. So long as the class is in a file with the same name, and it's in one of the directories Rails looks for classes in, you just use the class as if it was loaded and Rails will load it automatically

Gareth
I've done that, but realized shortly after, It only loads the model if it shares the same name as the controller. My model's name bears no resemblance to the controller's name, so it never gets loaded.
Robert Hurst
No that's not true. The controller isn't important here. If there's still a problem it's elsewhere. What happens if you open up ./script/console and type the name of your model?
Gareth
I typed config and all it does is read out what I typed in>> Config=> Config
Robert Hurst
Ah, I should have noticed the name of the class before. See my other answer
Gareth
A: 

Presumably, if you want to load a piece of information with a particular key you could use Config.find_by_key('the_key_you_want') to get the record in question.

I'm not sure that this would be the best way to handle your configuration, but it really depends on how your system needs to work.

EDIT:

Didn't see your update to the question before I posted my answer, seems like I misunderstood what you meant. Leaving this answer here in case it's useful, Gareth's answer seems like a fair answer.

fd
+2  A: 

The problem here is actually the name of the model. Config is used by other Rails classes - see the list of reserved names on the Rails wiki

Gareth
ooooh hahaha thats man thats very helpful, cheers. (Yay I can go have fun again!)
Robert Hurst
+1  A: 

You can add before_filter in ApplicationController:

before_filter :load_config

...
private
def load_config
  something
end

By default all controllers in Rails inherits from ApplicationController, so all controllers will execute load_config method at the begining.

By the way I really like rails-settings gem/plugin for configuration. It is probably something that you need. And it loads data when it is needed, so you don't have to load config in each controller, but just when you need some value, then you just do:

Settings.key

and you get what you want.

klew
I'll ad this to my gists thanks
Robert Hurst