我使用脚手架来构建我的RoR应用程序,然后添加了另一个名为apply_configs的控制器操作。它工作得很好(我添加到控制器方法中的所有操作都执行得很好,我可以从服务器上的日志看出这一点),但我不能让它在执行后呈现正确的页面。我将以下代码添加到控制器文件中apply_configs方法的末尾
respond_to do |format|
if @l2vpn.update_attributes(params[:l2vpn])
format.html { render action: "show", notice: 'L2vpn was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @l2vpn.errors, status: :unprocessable_entity }
end
end在服务器上,我可以看到这些日志
Started GET "/l2vpns/apply_configs? <long list of params goes here> " for 172.24.67.151 at 2012-03-16 11:32:01 -0700
Processing by L2vpnsController#apply_configs as */*
Parameters: { <long comma separated list of params goes here> }
L2vpn Load (0.4ms) SELECT "l2vpns".* FROM "l2vpns" WHERE "l2vpns"."id" = ? LIMIT 1 [["id", 1]]
Rendered l2vpns/show.html.erb within layouts/application (1.9ms)
Completed 200 OK in 112ms (Views: 12.4ms | ActiveRecord: 1.2ms)但实际上,与日志显示不同的是,我的浏览器并不显示show.html.erb的内容,浏览器的页面是不变的。我的目标是在执行apply_configs之后显示show.html.erb。
有谁知道如何实现这一点,为什么上面的配置对我来说不能像预期的那样工作?
更新jdl注释后的代码
class L2vpnsController < ApplicationController
respond_to :js, :html, :json
# GET /l2vpns/1
# GET /l2vpns/1.json
def apply_configs
@l2vpn = L2vpn.find(params[:id])
<more code goes here>
flash[:notice] = "Configs applied successfully!"
respond_with(@l2vpn, :location => l2vpns_url)
end
<other controller action definitions go here>
end发布于 2012-03-17 02:56:55
核心问题是在更新对象后没有重定向。看一看this Railscast on Rails 3 controllers,特别是处理respond_with的部分,它将为您处理大部分工作。
发布于 2012-03-17 05:24:00
据我所知,您希望重定向到show操作,而不是呈现show模板。通过直接呈现show模板,您不会收集模板正确呈现所需的数据,例如模型本身,因为这是由Controller.show方法完成的。
因为我不知道如何传递受影响模型的id,所以我假设它是作为名为:id的参数传递的。
然后,您的重定向将看起来像这样,假设您在同一个控制器中(否则,使用:controller => 'controller'传递控制器
format.html { redirect_to :action => 'show', :id => params[:id], :notice => 'L2vpn was successfully updated.' }第二种方法虽然我个人并不使用,但实际上是直接呈现显示模板,但是您需要复制(或重构并调用)在Controller.show方法中运行的大多数相同的代码。更准确地说,您需要运行为视图提供数据的代码部分。
例如:
@model = Model.find(params[:id])
format.html { render action: "show", notice: 'L2vpn was successfully updated.' }发布于 2012-03-22 01:07:11
我在胡乱猜测,将GET请求改为POST,这可能会解决这个问题。
我猜你的“”超过了GET请求允许的字符数,你的浏览器就会卡住。
https://stackoverflow.com/questions/9742855
复制相似问题