在我的应用程序中,我有一个小框出现在每个页面上,检查用户发出的请求的状态.如果随时接受请求,则应自动将用户带到某个页面.到目前为止这是我的代码:
<% offersMade.each do |w| %>
<% if w.accepted == true %>
<% redirect_to offer_path(:email => "email@gmail.com") %>
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
但是我收到了这个错误:
undefined method `redirect_to' for #<ActionView::Base:0x1042a9770>
Run Code Online (Sandbox Code Playgroud)
是否无法在视图中使用redirect_to?如果没有,我还能用其他东西吗?谢谢阅读.
Sal*_*lil 31
redirect_to是ActionController :: Base Class的一种方法,因此您无法在ActionView中使用它.
你可以尝试以下
<% if w.accepted == true %>
<script type="text/javascript">
window.location.href="/logins/sign_up" // put your correct path in a string here
</script>
<% end %>
Run Code Online (Sandbox Code Playgroud)
编辑了email参数
window.location.href="/logins/sign_up?email=<%= w.email %>"
Run Code Online (Sandbox Code Playgroud)
对不起,我不知道红宝石中是否有任何东西.
err*_*hpd 20
如果要从视图中使用redirect_to,请执行以下方法:
语法: <%controller.redirect_to path%>
示例: <%controller.redirect_to users_profile_path%>
视图中的代码可以移动到控制器中,这将使redirect_to可用.
class ApplicationController < ActionController::Base
before_action :check_for_accepted_offer
def check_for_accepted_offer
if Offer.any? { |o| o.accepted }
redirect_to offer_path(:email => "email@gmail.com")
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果OP想要在接受商品时立即更改URL,则答案中显示的Ruby代码都不会有帮助,因为它仅在页面加载时进行评估.OP需要设置某种轮询或推送策略,以便在接受要约时提醒浏览器,然后使用另一个答案中发布的JavaScript重定向方案:
window.location.href="/logins/sign_up?email=<%= w.email %>"
Run Code Online (Sandbox Code Playgroud)
虽然,这并没有回答这个问题:"我如何在视图中使用redirect_to",我认为这个答案最终会对OP更有用.当我应该在控制器中执行重定向时,我偶然发现了使用此答案重定向到另一个页面的人.