开发者

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.


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]


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜