How do I write a full path in a controller in Rails 3?
I need to write the full path so need to know what the rails_root domain is. How do I do that? For example:
string = "{RAILS_ROOT}/vendors/#{@vendor.id}"
What is the equivalent of "RAILS_ROOT" to give 开发者_JS百科me what the full domain is for my application? So that in development it would subsstitute localhost:3000 and on my heroku site the right full domain?
You should always avoid, if possible, hard-coding your path, because it is less flexible and more prone to result in broken links in the future. Plus, you can use Rails routing, which is an elegant way to generate everything cohesively in Rails without any need to create the composite parts yourself.
If you have your routes set up properly, you should be able to call:
link_to "View vendor", vendor_url(@vendor.id)
Vendor_url(@vendor.id)
in Rails gives you your full URL, which you can then contain in your string
variable. Here's how to generate the routes needed for the above:
# in routes.rb
resources :vendors
Try:
File.realpath(RAILS_ROOT)
You could access the request object. request.host_with_port would give you the hostname and port. request.protocol will give you the protocol (http:// or https://). request.fullpath will give you the path with query params.
精彩评论