Variable available for anything in a controller in Rails

I don't know if it was bad form or not, but I needed to set a file path accessible to all objects in my controller actions. One action in the controller creates the file and saves it in the path. Another action is serving the file using send_file. The only place where I store my variables is along with the object in the model. However, it seems silly to store the url arbitrarily as the first object, or copy the url across all objects. What's the best way to do this?

Hope this was clear.

+2


source to share


3 answers


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

session[:file_path] = generate_file!

      



... the user navigates to the next page ...

send_file session[:file_path]

      

+6


source


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



+1


source


The answer depends on your context. Here are some general tips:

If there is one file per model, you need to store one path for each model that has it.

If one file is shared by multiple models, but your objects are associated with a hierarchy, you need to store it on a "father object" - a volume that has_many others. Other objects will have to do self.parent.file_path.

Finally, if the same file is being used by multiple unrelated models, then I don't know what to suggest, except that there might be a better way to organize your models.

What objects are you trying to preserve and what are the relationships between them?

0


source







All Articles