Base URL of Rails app in Model

本秂侑毒 提交于 2021-01-26 06:49:40

问题


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


回答1:


You may use environment variables:

in environment

ROOT_URL=http://myapp.com

in-app

ENV['ROOT_URL']



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



来源:https://stackoverflow.com/questions/16305453/base-url-of-rails-app-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!