0

I an new in ruby and rails.

Following the guide in ror document,I create the blog application.

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?

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?

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

4
  • Have you tried reading some docs? Commented Feb 2, 2012 at 13:32
  • I do not mean the function of the method,but the expression here. Commented Feb 2, 2012 at 13:38
  • You need some basic ruby education, it will clear this up faster than anything else. mislav.uniqpath.com/poignant-guide Commented Feb 2, 2012 at 13:56
  • Check Ruby for Rails book by David Black Commented Feb 2, 2012 at 14:55

1 Answer 1

1

The respond_to method helps you to deliver the content in the format requested. For example, if you call /posts/1.json, the response would be a JSON file. If it's /posts/1.html, the response would be an HTML page. The default when no extension is provided is to render 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 { 
    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. In the method you provided, render json: @post tells Rails to render it immediately instead of looking for a file.

Sign up to request clarification or add additional context in comments.

2 Comments

I know this render different result according to the request type(json or html),I just can not understand this syntax. so format here is an object? and format.json is a method,and the {xx} is the argument of block type? and inside the block,the render is another method name,and the json:@post is the argument?
@hguser, your assumptions about what's method and what's arguments in that case are right if that's what you're asking about. render json: @post is equivalent of render({ :json => @post }) if that'd make things clearer for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.