Hommer Smith
Hommer Smith

Reputation: 27852

Base URL of Rails app in Model

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

Upvotes: 10

Views: 23286

Answers (2)

earth2jason
earth2jason

Reputation: 717

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']

Upvotes: 15

Danil Speransky
Danil Speransky

Reputation: 30453

You may use environment variables:

in environment

ROOT_URL=http://myapp.com

in-app

ENV['ROOT_URL']

Upvotes: 3

Related Questions