开发者

can someone explain to me what respond_to does? (Rails)

So when one generates scaffodl, the controller automatically creates these blocks(?) like this

respond_to do |format|
      format.html
      format.xml  { render :xm开发者_StackOverflow社区l => @c }
    end

what does this really do and how come it has format.html and format.xml? What does each do?


It defines that the current action will respond to various formats (the action's content can be rendered in many ways, not only plain old HTML).

  • If you open your browser and type /my/path/to/action.html, it will render HTML (from the template);
  • If you type /my/path/to/action.xml, it will render XML using { render :xml => @c }. XML will be generated by Rails by calling the to_xml method on the @c variable;
  • However, if you point to /my/path/to/action.json, it will throw a 404 error.


Rails uses the MIME type of the request determined by the Accept header or format (/controller/action/5.xml; /controller/action/5.html; /controller/action/5.json; etc… ) to determine the response format of the controller action that maps to the requested url.

This way rails can automagically render different content formats for many types of requests to the same controller action.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜