【问题标题】:Rails 3 respond_with: show "show" layout on resource creationRails 3 respond_with:在资源创建时显示“显示”布局
【发布时间】:2011-12-01 21:39:42
【问题描述】:

我有一个comment 资源。我有一个控制器来处理respond_with,现在,它应该提供所有 JSON 响应(这是正确发生的)。我正在使用Rabl 来处理我的 JSON/XML 渲染,并且我正在把事情弄干一点。我有 正确的 方式,我希望在 comments/show.rabl 处呈现 comment

object @comment

attributes :id, :body, :a_few_more_things

当对 /comments/ 进行 POST 调用(触发我的控制器上的 create 方法)时,我希望 Rails 以与 show 视图(上图)相同的格式返回 comment。我有,在我的 create 函数中......

def create
  # Skip some code, save it, ya-da ya-da
  respond_with(@comment, :layout => 'comments/show')
end

这行不通;它只是返回一个带有所有属性的comment 的平面 JSON 实现。它没有在comments/show.rabl 使用我的show.rabl如何让我的create 操作以使用show.rabl 作为布局返回@comment?

我看到this post指定了布局文件的完整路径和扩展名;我不应该那样做,不是吗?我是否使用了错误的:symbol_option?应该是:location吗?

【问题讨论】:

标签: ruby-on-rails ruby json rabl


【解决方案1】:

我可以通过在 comments/create.rabl 创建 Rabl 模板来解决此问题。

object @comment

extends "comments/show"

这就是她写的全部内容。 Rails 寻找create.rabl 视图,它接受一个对象并只呈现comments/show.rabl 中定义的字段。

感谢Martin Harrigan 提醒我我的问题还有待解决!

【讨论】:

    【解决方案2】:

    您可以使用,保持干燥:

    render :show, :status => :created
    

    【讨论】:

      【解决方案3】:

      在 Rails4 中你可以指定模板:

      def create
        respond_with @comment, status: :created, template: 'comments/show'
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-15
        • 1970-01-01
        • 1970-01-01
        • 2011-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多