Rails中redirect后如何调整页面行为?如何判断视图是否来自重定向?
Rails 重定向后视图状态判断的简洁实现方案
以下是3种符合Rails开发惯例的实现方式,按推荐优先级排序:
- 方案1:使用Rails原生
flash传递状态(最推荐)flash是Rails专门为重定向场景设计的临时数据存储,数据在一次重定向后自动清除,无需手动处理残留。
修改你的updateaction代码如下:
# PATCH/PUT /stuffs/1 or /stuffs/1.json def update respond_to do |format| if @stuff.update(stuff_params) # 重定向时传递状态标记和需要展示的结果数据 format.html { redirect_to action: 'index', flash: { from_update: true, updated_stuff: @stuff } } format.json { render :show, status: :ok, location: @stuff } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @stuff.errors, status: :unprocessable_entity } end end end
在Index视图中直接判断flash值即可控制结果展示:
<% if flash[:from_update] %> <!-- 你要展示的返回结果区块 --> <div class="result"> 更新成功,最新内容:<%= flash[:updated_stuff].content %> </div> <% end %> <!-- 原有表单代码保持不变 -->
- 方案2:重定向携带自定义查询参数
如果需要更直观的参数判断,可直接在重定向的URL上追加自定义参数:
format.html { redirect_to action: 'index', from_update: 1, stuff_id: @stuff.id }
视图中直接判断params[:from_update].present?即可,这种方式参数会暴露在浏览器地址栏,适合不需要隐藏状态的场景。
- 方案3:放弃重定向直接渲染Index视图
如果不需要遵守Post/Redirect/Get规范,完全可以在更新成功后直接渲染Index视图,减少一次HTTP请求:
def update respond_to do |format| if @stuff.update(stuff_params) # 声明视图需要的控制变量和结果数据 @show_result = true @updated_stuff = @stuff format.html { render :index } format.json { render :show, status: :ok, location: @stuff } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @stuff.errors, status: :unprocessable_entity } end end end
视图中判断<% if @show_result %>即可展示结果,这种方式需要注意给表单输入项设置默认值为用户提交的参数,避免输入内容丢失。
内容的提问来源于stack exchange,提问作者RichT
相关产品推荐
相关产品推荐

