简体   繁体   English

这个Rails代码中的“respond_to”,“do”和“| format |”是什么?

[英]What is “respond_to” and “do” and “|format|” in this Rails code?

class PostsController < ApplicationController
  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end
...
  • What exactly is "respond_to" Is it part of rails? 究竟什么是“respond_to”它是rails的一部分吗?
  • What is "do" and"|format|"? 什么是“做”和“|格式|”? Why are there vertical separators around format? 为什么格式周围有垂直分隔符?
  • How come Rails knows about the Post model? Rails如何知道Post模型? I didn't import that model. 我没有导入该模型。 (In Python/Django, you have to import a model before you can use it) (在Python / Django中,您必须先导入模型才能使用它)

This is from the Ruby on Rails tutorial: http://edgeguides.rubyonrails.org/getting_started.html#setting-the-application-home-page 这是来自Ruby on Rails教程: http//edgeguides.rubyonrails.org/getting_started.html#setting-the-application-home-page

respond_to is a rails specific method that defines how requests for different formats (like xml and html) are responded to. respond_to是一种特定于rails的方法,用于定义如何响应不同格式(如xml和html)的请求。 The do and |format| do|format| delineate a ruby block, with do acting like a open brace and end as a closing brace, and |format| 划定一个红宝石块,与do像个开括号,并end作为一个右括号,和|format| defines the block variable that gets its value from the yield statement within responds_to . 定义block变量,该变量从responds_toyield语句获取其值。

the "do" is a RUBY block, and the "|format|" “do”是一个RUBY块,而“| format |” could be anything, its just a variable to use inside that block, here is another example: 可以是任何东西,它只是在该块内使用的变量,这是另一个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM