【问题标题】:Rails after form submitted redirect to empty form page again提交表单后的Rails再次重定向到空表单页面
【发布时间】:2014-02-26 13:19:08
【问题描述】:

我正在构建一个带有简单联系表单的页面。用户提交表单后,我希望它重定向回完全相同的页面,然后显示成功消息。但我不使用节目的原因是因为我想要一个全新的联系表(不是他们已经提交的),以防他们想提交另一个请求。但是,redirect_to 似乎不起作用。

感谢您的帮助!

我的控制器(注意我也尝试了 render 而不是 redirect_to)

def create
    @contact= Contact.new(secure_params)
    if @contact.save
      flash[:success] = "Thanks! I'll be in touch soon!"
      redirect_to 'new'
    else
      render 'new'
    end
end

我的看法

<body>
<h1> opening text </h1>

<!--prints success message, making it a hash just in case other messages need to be added in the future -->
<% flash.each do |key, value| %>
    <div class="alert alert-<%= key %>"><%= value %></div>
<% end %>


<%= form_for @contact do |f| %>
<!--form code below -->

【问题讨论】:

    标签: html ruby-on-rails forms post http-redirect


    【解决方案1】:

    改成

    if @contact.save
      flash[:success] = "Thanks! I'll be in touch soon!"
      redirect_to :action => 'new'
    else
      render :action => 'new'
    end
    

    redirect_to 期望 url/相对路径作为字符串,或指向 url 的哈希

    例如:

    "/user/10"
    "http://localhost:3000/users/new" 
    or  {:controller => 'users', :action => 'new'}
    

    但是当你给redirect_to 'new'时,它正在寻找'/new'

    【讨论】:

    • 效果很好,我能问一下为什么会这样吗?似乎它正在做与“新”完全相同的事情,不是吗?另外,我不需要第二个动作 => 渲染中已经开始工作的新动作。
    • @james 更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2020-02-18
    • 2014-03-10
    • 1970-01-01
    • 2014-02-05
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多