我可以在RoR的视图中使用redirect_to吗?

时间:2010-07-03 05:57:11

标签: ruby-on-rails

在我的应用中,我的每个页面上都有一个小框,检查用户发出的请求的状态。如果随时接受请求,则应自动将用户带到某个页面。到目前为止,这是我的代码:

 <% offersMade.each do |w| %>
  <% if w.accepted == true %>
   <% redirect_to offer_path(:email => "email@gmail.com") %>
  <% end %>
 <% end %>

但是我收到了这个错误:

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

是否无法在视图中使用redirect_to?如果没有,我还能用其他东西吗?谢谢你的阅读。

5 个答案:

答案 0 :(得分: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 %>

已修改电子邮件参数

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

抱歉,我不知道红宝石中是否有任何东西。

答案 1 :(得分:18)

如果要在视图中使用redirect_to,请执行以下方法:

语法:&lt;%controller.redirect_to path%&gt;

示例:&lt;%controller.redirect_to users_profile_path%&gt;

答案 2 :(得分: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@gmail.com")
    end
  end
end

如果OP想要在接受商品时立即更改URL,则答案中显示的所有Ruby代码都不会有帮助,因为它仅在页面加载时进行评估。 OP需要设置某种轮询或推送策略,以便在接受要约时提醒浏览器,然后使用另一个答案中发布的JavaScript重定向方案:

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

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

答案 3 :(得分:1)

redirect_to不是ActionView的方法。它是ActionController的一种方法。你可以在页面加载或其他一些事件上使用Javascript window.location.href将你的用户带到另一个页面。

答案 4 :(得分:0)

是的,您可以从视图中调用controller.redirect_to来获取您想要的内容,而无需呈现整个响应,然后在客户端上使用javascript发出新请求。

在您的示例中,这看起来像:

<% offersMade.each do |w| %>
  <% if w.accepted == true %>
    <% controller.redirect_to offer_path(:email => "email@gmail.com") %>
  <% end %>
<% end %>

请注意,此controller.redirect_to不会突破您的循环,因此您可能希望break,并且您可能希望确保视图的其余部分仅有条件地呈现如果你没有重定向。

(免责声明:我不一定宽恕这种技巧。如你所知,你最好在你的控制器或助手中做这件事。)