Ruby-on-rails 如何使用 Rails 重定向到外部网站?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1028923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:23:21  来源:igfitidea点击:

How do you redirect to an external website with rails?

ruby-on-railsruby

提问by Aaron

I want links that when hovered over you see the link to look something like this:

我希望将鼠标悬停在上面的链接看起来像这样:

http://www.website.com/redirct_to=linkID2(maybe not exactly like that but try to get the idea)

http://www.website.com/redirct_to=linkID2(可能不完全一样,但试着理解)

I have a form area in my blog that I can input a website url but I want to make it redirect_to an external website when it shows the post.

我的博客中有一个表单区域,我可以输入网站 url,但我想让它在显示帖子时重定向到外部网站。

回答by Ben Hughes

redirect_to "https://website.com"

should do it as long as protocol is included. For added flexibility, you can parse it with URI to ensure that all fields are correct. You might want to URI.encode/URI.decode

只要包含协议就应该这样做。为了增加灵活性,您可以使用 URI 对其进行解析以确保所有字段都正确。你可能想要 URI.encode/URI.decode

回答by Simone Carletti

Create a new model, for example called Link, to store the URLs you want to redirect to. Then generate a new controller (you can use scaffold to generate controller and model at the same time) and change the show action in order to fetch the record with given ID and redirect_to @link.url.

创建一个新模型,例如称为 Link,以存储您要重定向到的 URL。然后生成一个新的控制器(您可以使用脚手架同时生成控制器和模型)并更改 show 操作以获取具有给定 ID 和 redirect_to @link.url 的记录。

If you don't want to use the #show action for this step, create a new action do handle the redirect (for example goto, redirect...).

如果您不想在此步骤中使用 #show 操作,请创建一个新操作来处理重定向(例如 goto、redirect...)。

回答by zenbakiak

redirect_to isn't available in views or is not a helper method, be sure to use it in your controllersbut if you really want to redirect from view, use the javascript solution

redirect_to 在视图中不可用或不是辅助方法,请务必在控制器中使用它,但如果您真的想从视图中重定向,请使用 javascript 解决方案

window.location.href=<%= post.link_url %>

window.location.href=<%= post.link_url %>