【问题标题】:Why does the Rails "new" action have an XML format directive?为什么 Rails 的“新”动作有 XML 格式指令?
【发布时间】:2010-03-16 21:24:30
【问题描述】:

我是 Rails 的新手,一直在关注rails webpage 上的教程。 使用脚手架指令创建“post”模型,我发现控制器中的new动作有一个针对XML格式的特殊指令:

def new
  @post = Post.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @post }
  end
end

我看不到在创建新帖子时支持 XML 请求的原因。浏览到 /posts/new.xml 不会返回任何内容。这样做的目的是什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    new 操作背后的原因只是为 xml 客户端提供默认数据(或其他,如果您愿意)。

    所有路由都在使用格式指令,除非您愿意,否则您不需要支持格式。

    上面的代码可能看起来像:

    respond_to do |format|
      format.html # renders new.html.erb
      format.xml  { render :xml => {:message => "XML is not supported"} }
      format.json { render :text => @post.to_json }
      format.js # renders new.js.erb
    end
    

    此外,这不仅限于new 操作,还可以在您的所有操作中使用。要使用的格式要么取自 url(如果路由设置为使用它),要么取自浏览器发送的 HTTP-Accept 标头。

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多