【问题标题】:what does the following code do?下面的代码是做什么的?
【发布时间】:2011-01-01 17:00:19
【问题描述】:

我创建了一个项目

demo
在 rails 中。然后我通过给
 rail_apps/demo> 脚本服务器产品标题创建了一个脚手架应用程序:stiring,description:text,url:string 

然后我给了

 http://localhost:3000/products/ 

products_controller.rb 包含以下代码

class ProductsController < ApplicationController
  # GET /products
  # GET /products.xml
  def index
    @products = Product.find(:all)

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

但我真的无法理解那四行代码。谁能给我一个领导?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:
    @products = Product.find(:all)
    

    从数据库中获取所有产品。

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

    是 RoR 中的常见模式。根据请求,控制器呈现不同的视图。例如,如果您请求 /products,它会将产品传递给只是一个 html 模板的 index.html.erb 视图。如果请求是/products.xml,它会将产品序列化为 XML 文件并将该文件作为响应发送。

    【讨论】:

    • 谢谢你 Darin,你能告诉我 respond_to 是不是一个循环吗?这似乎是一个循环。在这种情况下,客户端无论如何都会请求一次。这里 do 循环的真正目的是什么?
    • @CHID,它不是一个循环,它是一个块。您可以查看following blog post以获得更详细的说明。
    • 您应该提到 /products 只是默认为 /products.html,“.html”和“.xml”被称为“格式”。
    【解决方案2】:

    要呈现index 操作,首先找到所有产品并将它们分配给变量@products,然后根据客户的需要使用HTML 或XML 进行响应(例如,如果URL 以.xml 结尾,则客户需要 XML。

    如果客户端需要 HTML,则渲染 index.html.erb(Rails 根据控制器名称和操作名称查找模板本身,因此 ProductsControllerindex 使 Rails 查找 app/views/products/index.html.erb

    如果客户端需要 XML,则从 @products 变量呈现 XML(Rails 可以通过查看其属性自动将 ActiveRecord 对象或对象数组序列化为 XML)。

    【讨论】:

    • response_to do |format| . . end 似乎是一种循环结构.. 它真的是一个循环吗?
    • 不,它更像是一个模式匹配子句。考虑 case/when(Java/JS/C++ 中的 switch/case)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2019-06-24
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多