Base URL of Rails app in Model
Solution 1
You may use environment variables:
in environment
ROOT_URL=http://myapp.com
in-app
ENV['ROOT_URL']
Solution 2
If you want to get the root URL in your model, what I did is call an ENV variable.
If you haven't already, go ahead and create .env in the root directory of your applicatoin and set in development to:
ROOT_URL=http://localhost
In your production environment set:
ROOT_URL=https://mydomain.com
Of course this is hard coded so the pitfall is that you need to remember to change this when changing domains and each environment's file must be different.
And be sure this is also in your gitignore since other sensitive data will be stored here.
In your model you call by: ENV['ROOT_URL']
Hommer Smith
Updated on September 04, 2020Comments
-
Hommer Smith over 3 years
In order to be able to see if a User has shared my page on Facebook, I want to be able to create this kind of URLs:
http://graph.facebook.com/?id=http://stylehatch.co/some_unique_user_token
Where http://stylehatch.co would need to be my base URL. I am thinking on having a method in the User model that will build and return that URL, but I can't access root_url from within my model.
How can I get the base URL of my application from a Model?
Say if my urls look like this:
http://myapp.com/users/new http://myapp.com/users/2/show
How can I get the "http://myapp.com" from my model? I have added:
include Rails.application.routes.url_helpers
in my model, but it seems that root_url is nil. Any thoughts? Is this correct to be a Model method, or should I place it in a helper?
Thanks
-
Hommer Smith about 11 yearsSperansky, do you think is correct to have that in the model though, and pass the url as a parameter? Or do you think this belongs to be in a helper?
-
maurice over 9 yearsIn the situation that the OP described, and in situations like sending out emails that link back to your site, you do generally need some part of your app (whether or not it's the model) to be aware of your application's base url. @earth2jason's answer below seems a good approach for that.
-
baash05 about 5 yearsThis is not a valid answer to the OP.