开发者

Rails 3 change path to url

开发者 https://www.devze.com 2023-04-05 09:14 出处:网络
I am passing a path as a parameter, so params[:path] would be name_path(:username => @user.name (I want to pass it as a path and not a url, so putting name_url in the params isn\'t what I want).

I am passing a path as a parameter, so params[:path] would be name_path(:username => @user.name (I want to pass it as a path and not a url, so putting name_url in the params isn't what I want).

Since you can only use redirect_to with a url, I need to change the path to a url before I can use redirect_to. How would I do this?

I found this method here

def path_to_url(path)
  "http://#{request.host_with_port_without_standard_port_handling}/#{path.sub(%r[^/],开发者_运维问答'')}"
end

But, this was written in 2008, and I want to know if there is a better way in Rails 3?


Updated copy from original path to url post btw: also works on Rails 2

# abs or /abs -> http://myx.com/abs
# http://grosser.it/2008/11/24/rails-transform-path-to-url
def path_to_url(path)
  "#{request.protocol}#{request.host_with_port.sub(/:80$/,"")}/#{path.sub(/^\//,"")}"
end


I think you can use a redirect_to with a path as long as its a route defined in the routes file for the current application. Thats seems to be the case from your question.

ie, name_path(:username => @user.name)

So the following should be valid.

redirect_to params[:path]


I ended up using

def path_to_url(path)
  "http://#{request.host}/#{path.sub(%r[^/],'')}"
end
0

精彩评论

暂无评论...
验证码 换一张
取 消