【问题标题】:Ruby on Rails show action not working from controllerRuby on Rails 显示操作无法从控制器工作
【发布时间】:2012-04-02 07:49:28
【问题描述】:

我使用脚手架来构建我的 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

【问题讨论】:

    标签: ruby-on-rails ruby methods controller rendering


    【解决方案1】:

    核心问题是更新对象后没有重定向。查看this Railscast on Rails 3 controllers,特别是处理respond_with 的部分,它将为您完成大部分工作。

    【讨论】:

    • 感谢 jdl。我实现了该教程中的更改,但我仍然得到完全相同的行为!
    • 请发布您的新控制器代码,如果您在您的模型中使用attr_accessible,也很高兴知道。
    • 感谢 jdl,我在原始问题的末尾粘贴了更新的控制器代码
    【解决方案2】:

    据我所知,您希望重定向到 show 操作,而不是呈现 show 模板。通过直接渲染 show 模板,您不会收集模板正确渲染所需的数据 [例如模型本身],因为这是通过 Controller.show 方法完成的。

    由于我不知道您如何传递受影响模型的 id,我假设它是作为名为 :id 的参数传递的。

    假设您在同一个控制器中,您的重定向将如下所示(否则,使用 :controller =&gt; 'controller' 传递控制器:

    format.html { redirect_to :action => 'show', :id => params[:id], :notice => 'L2vpn was successfully updated.' }
    

    第二个选项 [虽然我个人不使用它] 是实际直接渲染显示模板,但是您需要复制(或重构和调用)大多数在 @ 中运行的相同代码987654328@ 方法。更准确地说,您需要运行向视图提供数据的部分代码。

    例如:

    @model = Model.find(params[:id])
    format.html { render action: "show", notice: 'L2vpn was successfully updated.' }
    

    【讨论】:

    • 感谢西蒙诺德伯格。我尝试了这两种方法,但都没有奏效。我可以执行显示操作(来自服务器上的日志),我看到一条日志显示“Rendered l2vpns/show.html.erb”,但我的浏览器不显示该文件的内容!
    【解决方案3】:

    我在猜测,将 GET 请求更改为 POST,这应该可以解决问题。

    我猜你的 " " 超过了 GET 请求所允许的字符数,你的浏览器会因此而窒息。

    【讨论】:

    • @fail markdown,将第二段更改为,我猜你的“长长的参数列表到这里”...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多