Rails respond_to 方法求解

mr_zou123 · 2013年08月31日 · 最后由 towonzhou 回复于 2013年09月01日 · 6297 次阅读

请教大家一个问题:在 ruby on rails 的 controller 里的方法中的 respond_to do |format| 这句什么意思?

匿名 #1 2013年08月31日

根据请求的格式,返回不同的数据……

嗯,谢谢!还有,他这种返回格式 format.json { render json: @person }后面的参数是什么意思

#1 楼 @francistm 嗯,谢谢!还有,他这种返回格式 format.json { render json: @person }后面的参数是什么意思

完整的话是这样的

respond_to do |format|
  format.json do
    render({ json: @person })
  end
end

#4 楼 @qhwa 哦,是这样的,谢谢你!

匿名 #6 2013年08月31日

#3 楼 @mr_zou123 你是指 @person 这个么?把 @person 对象按照 JSON 的格式输出吧,相当于 render :text => @person.to_json 一样。

#1 楼 @francistm 哦,明白了,谢谢你!

@francistm render json: @person 应该是相当于 render json: @person.to_json

respond_to 是根据请求的头信息来判断来调用那种 block,实现方法类似

def xml
  yield if self.accept_header == "text/xml"
end

def html
  yield if self.accept_header == "text/html"
end

def json
  yield if self.accept_header == "text/json"
end

format 实际是一个 http 请求包装程序。

mr_zou123 关闭了讨论。 11月02日 22:24
需要 登录 后方可回复, 如果你还没有账号请 注册新账号