环境:ruby 1.9.3p0,rails 3.2.6
介绍rails3-controller除了默认的respond_to外的respond_with
使用rails脚手架生成的controller默认是这样的
def index @students = Student.all respond_to do |format| format.html # index.html.erb format.json { render json: @students } end end
通过format来匹配浏览器发送的请求,返回响应的页面
respond_with的用法:
在controller首行加上要处理的请求类型,比如 respond_to :html, :json
class StudentsController < ApplicationController respond_to :html, :json #新增 end
然后,index函数可以使用respond_with,参数就是@students
def index @students = Student.all respond_with(@students) end
如果向设置返回页面,使用参数 :location
class StudentsController < ApplicationController respond_to :html, :json # GET /students # GET /students.json def index @students = Student.all respond_with(@students) end # GET /students/1 # GET /students/1.json def show @student = Student.find(params[:id]) respond_with(@student) end # GET /students/new # GET /students/new.json def new @student = Student.new respond_with(@student) end # GET /students/1/edit def edit @student = Student.find(params[:id]) end # POST /students # POST /students.json def create @student = Student.new(params[:student]) if @student.save flash[:notice] = 'Student was successfully created.' end respond_with(@student,:location=> students_url) end # PUT /students/1 # PUT /students/1.json def update @student = Student.find(params[:id]) if @student.update_attributes(params[:student]) flash[:notice] = 'Student was successfully destroy.' end respond_with(@student, :location=> students_url) end # DELETE /students/1 # DELETE /students/1.json def destroy @student = Student.find(params[:id]) @student.destroy flash[:notice] = 'Student was successfully destroy.' respond_with(@student) end end
respond_with 支持block,用来重写默认的返回页面
def update @student = Student.find(params[:id]) if @student.update_attributes(params[:student]) flash[:notice] = 'Student was successfully destroy.' end respond_with(@student, :location=> students_url) do |format| format.html { render :text => "hello, rails"} end end
这样再次更新数据的时候, 返回的结果就是 hello, rails