rails:redirect_to呈现但不重新加载新页面

时间:2019-04-24 17:00:36

标签: ruby-on-rails redirect

我希望我的应用程序在更新一个对象时显示所有关联对象的列表,因此我想在更新完成后加载index操作。

我尝试格式化块,删除格式,渲染和redirect_to。它们全部都保留在编辑页面上

更新操作:

  def update
    respond_to do |format|
      if @business_category.update_attributes(business_category_params)
        format.html {redirect_to admin_business_categories_path}
        return
      end
    end
  end

修改视图:

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <%= link_to 'Back to categories', admin_business_categories_path %>
    </div><!-- .col -->
    <%= simple_form_for(@business_category, url: admin_business_category_path(@business_category), remote: true, html: { class: '' }) do |f| %>
      <%= render 'form', f: f %>
    <% end %>
  </div><!-- .row -->
</div><!-- .container -->

_form部分:

<div class="col-xs-12 col-sm-10 col-md-10">
  <%= f.input :name, label: 'Category Name' %>
</div>

<div class="col-xs-12 col-sm-2 col-md-2">
  <div class="btn-group-vertical" role="group" aria-label="...">
    <button id="businessCategoryCancelButton" class="btn btn-warning">CANCEL</button>
    <%= f.submit 'SAVE', class: 'btn btn-success' %>
    <br>
  </div>
</div>

redirect_to处,控制台中将显示一条消息:

No template found for Admin::BusinessCategoriesController#update, rendering head :no_content
Completed 204 No Content in 1505ms (ActiveRecord: 1.0ms)

我不知道为什么它要寻找更新模板或为什么不将其重定向到索引操作

我试图了解格式的工作方式以及它是否/为什么与重定向冲突。任何建议都会有所帮助

2 个答案:

答案 0 :(得分:1)

因为您正在发出AJAX调用(表单上的remote: true)。

您有以下选择:

  • format.js添加到控制器
  • 从表单定义中删除remote: true,从控制器中删除respond_to
def update
  if @business_category.update_attributes(business_category_params)
    redirect_to admin_business_categories_path
  else
    render :edit
  end
end

答案 1 :(得分:0)

simple_form_for(@business_category, url: admin_business_category_path(@business_category), remote: true, html: { class: '' })

在您的表格中,您提到了remote: true。它将您的请求作为JS请求处理。在您的控制器中,您提到了format.html {redirect_to admin_business_categories_path},但是它将以format.js的形式处理,并寻找update.js.erb文件来处理响应,因为您的请求格式是“ JS”而不是“ HTML” ,因此显示错误。

您必须将请求作为HTML请求发送。

根据您的实现。我认为您只是想在成功的情况下进行重定向,并在出现错误的情况下再次呈现编辑页面。

您必须进行2次更改。

  1. 删除遥控器:由于不符合您的要求,因此从表单中删除
  2. 在其他情况下,format.html { render :edit }添加行update_attributes()
相关问题