V_H
V_H

Reputation: 1793

Variable that's accessible to anything in the controller in Rails

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.

Upvotes: 2

Views: 310

Answers (3)

kikito
kikito

Reputation: 52718

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?

Upvotes: 0

cwninja
cwninja

Reputation: 9778

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]

Upvotes: 6

Jim McKerchar
Jim McKerchar

Reputation: 156

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.

Upvotes: 1

Related Questions