2010-07-03 59 views
16

在我的应用程序中,我有一个出现在每个页面上的小框,用于检查用户发出的请求的状态。如果任何时候接受请求,那么用户应该自动被带到某个页面。这是到目前为止我的代码:我可以在RoR的视图中使用redirect_to吗?

<% offersMade.each do |w| %> 
    <% if w.accepted == true %> 
    <% redirect_to offer_path(:email => "[email protected]") %> 
    <% end %> 
<% end %> 

但我发现了这个错误:

undefined method `redirect_to' for #<ActionView::Base:0x1042a9770> 

是没可能给用户redirect_to的一个看法?如果不是,还有什么我可以使用的?谢谢阅读。

回答

29

redirect_to是一个ActionController :: Base类的方法,所以你不能在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 %> 

编辑的电子邮件参数

window.location.href="/logins/sign_up?email=<%= w.email %>" 

对不起,我不知道是否有在红宝石的事情。

+0

谢谢,这个作品很棒。你知道是否有一种方法可以在URL构造中使用RoR变量?在我最初的代码中,我有(:email =>“[email protected]”),我不确定我是否可以在JavaScript中做类似的事情? – ben 2010-07-03 06:16:33

+0

检查我编辑的答案。 – Salil 2010-07-03 06:20:06

+0

非常感谢,它的工作原理!我不认为你可以在js中嵌入红宝石,但显然你可以。再次感谢! – ben 2010-07-03 06:25:05

1

redirect_to不是ActionView的方法。它的一种方法ActionController。您可以在页面加载或某些其他事件中使用Javascript window.location.href将用户转到其他页面。

+1

感谢您的帮助,不知道这一点。 – ben 2010-07-03 06:17:06

6

视图中的代码可以移入控制器,这将使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 protected]") 
    end 
    end 
end 

如果OP要立即更改URL时的报价被接受,然后在没有答案表示将帮助,因为加载页面时,只计算了Ruby代码。该任择议定书需要安装某种形式的投票或推动战略的提醒浏览器时的报价已经被接受,然后使用JavaScript重定向张贴在另一个答案方案:

window.location.href="/logins/sign_up?email=<%= w.email %>" 

虽然,这并不回答这个问题:“我怎样才能在视图中使用redirect_to”,我认为这个答案最终会对OP更有用。我偶然发现有人使用这个答案重定向到另一个页面,当重定向应该在控制器中执行时。

0

是的,你可以从你的视图中调用controller.redirect_to来得到你想要的,而不必渲染整个响应,然后在客户端使用javascript来发出新的请求。

在您的例子,这将是这样的:

<% offersMade.each do |w| %> 
    <% if w.accepted == true %> 
    <% controller.redirect_to offer_path(:email => "[email protected]") %> 
    <% end %> 
<% end %> 

注意这controller.redirect_to不会打破你的循环,所以你可能会想break,你可能会想,以确保如果你没有重定向,你的视图的其余部分只是有条件地呈现。正如其他人所说的那样,在控制器或助手中这样做会更好。)

16

如果你想使用redirect_to时从视图中,做到这一点的方法:

语法: <%controller.redirect_to路径%>

例如: <%controller.redirect_to users_profile_path%>

+3

这是一个很好的方式来做到这一点本地化,避免JavaScript! – 2017-04-08 22:52:43

+0

当我使用这个,我需要单词'控制器',而不是控制器的名称。这很好。 – 2017-10-17 18:46:49