简体   繁体   English

Rails生成的ruby源代码

[英]the ruby source code generated by rails

I an new in ruby and rails. 我是红宝石和铁轨的新手。

Following the guide in ror document,I create the blog application. 按照ror文档中的指南,我创建博客应用程序。

Howver when I see the code generated,I found that I can not understand them,for exmpale: 但是,当我看到生成的代码时,例如发现我无法理解它们:

  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @post }
    end
  end

The repond_to is a method(isn't it?),and the following block is the argument? repond_to是一个方法(不是吗?),下面的块是参数吗?

However what does the code inner the block mean? 但是,该块内部的代码是什么意思?

      format.html # show.html.erb
      format.json { render json: @post }

Is the format.html is the name of the method or something else? format.html是方法的名称还是其他名称?

ANd how about the { render json: @post } >? { render json: @post } >怎么样?

The respond_to method helps you to deliver the content in the format requested. respond_to方法可帮助您以请求的格式交付内容。 For example, if you call /posts/1.json , the response would be a JSON file. 例如,如果调用/posts/1.json ,则响应将是JSON文件。 If it's /posts/1.html , the response would be an HTML page. 如果是/posts/1.html ,则响应将是HTML页面。 The default when no extension is provided is to render HTML. 没有提供扩展名时的默认值是呈现HTML。

The format.json method tells Rails what to do when requested that extension, like for example, if for every JSON request you would like to increase a counter, but not for HTML requests, you could do: format.json方法告诉Rails在请求该扩展名时该怎么做,例如,如果您想为每个JSON请求增加一个计数器,而不是为HTML请求增加计数器,则可以执行以下操作:

format.json { 
    counter = counter + 1
    render json: @post
}

If you don't provide a block to the format.json method, Rails automagically will try and look inside views/posts/ for a show.json.erb file, and render that. 如果不为format.json方法提供块,Rails会自动尝试在views/posts/查找show.json.erb文件,然后进行渲染。 In the method you provided, render json: @post tells Rails to render it immediately instead of looking for a file. 在您提供的方法中, render json: @post告诉Rails立即渲染它,而不是寻找文件。

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

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