views:

165

answers:

3

I don't know if this is bad form or not, but I needed to set a file path that's accessible to all objects within actions in my controller. One action in the controller creates a file and stores it in a path. Another action serves the file using send_file. The only place I have been storing variables is along with an object in the model. However it seems really silly to store a URL in arbitrarily the first object, or copy the url over all objects. What's the best way to do this?

I hope this was clear.

+1  A: 

You could create a method in your application controller that returns the path. This method will then be available throughout your controllers. Don't know if this is necessarily "best practice" but it works for me.

Jim McKerchar
+6  A: 

If this is a file path that is specific to the user of the site, so each user has a different path, you can store it in the session.

session[:file_path] = generate_file!

…user goes to the next page…

send_file session[:file_path]
cwninja
I deleted my answer and gave this a +1. I hadn't thought about a different file per session, but that's clearly going to be an issue which this method solves nicely.
jdl
It's only for the admin user (there's only one admin) so I don't have to worry about each user... is this method still best for this case?
Stacia
Should be. Any other method that would only be for just one user would probably be more complicated. Putting the file path in the request params is a security risk, so don't do that.
cwninja
A: 

The answer depends on your context. Here is some generic advice:

If there's one file per model, then you need to store one path on each model that has it.

If there's one file shared by several models, but your objects are relatd on a hierarchy, you need to store it on the "father object" - the one that has_many others. The other objects will have to do self.parent.file_path.

Finally, if there's one file used by several non-related models, then I don't know what to suggest, except that maybe there's a better way to organize your models.

What objects are you trying to store, and what relationships are between them?

egarcia