Rails Response
Response method
Method | Description |
---|---|
render | |
redirect_to | |
send_file | |
send_data | |
head |
render
There are some examples
Call template which is different from action name
render action: 'index' # template index.html.erb
Call other directory template
render template: 'hello/view' hello/view.html.erb
Call template out side of application(using path)
render file: 'data/template/list'
inline response
text
render text: ''
inline
argument text is defined as ERB template
render inline: 'Request Info : <%= debug request.headers %>'
redirect_to
Redirect examples
redirect_to 'http://google.com.sg' redirect_to action: :index redirect_to controller: :hello, action: :list redirect_to item_path # view helper redirect_to :back # back one page
send file
Read file(path) and send client
send_file 'xxx.zip' send_file 'xxx.jpg', type: 'image/jpeg', disposition: :inline send_file 'xxx.pdf', filename: 'xxx.pdf'
Don’t use file path directly from the client.
File path should save in server side(db, or something)
send data
Receive binary data and display
(image file etc…)
def show_photo # if no parameter set 1 id = params[:id] ? params[:id] : 1 @item = Item.find(id) send_data @item.photo, type: @item.ctype, disposition: :inline end
status code
status code only
render nothing: true, status: 404
Or
head 404
status code list
Rails code | status code |
---|---|
:ok | 200 |
:created | 201 |
:created | 301 |
:found | 302 |
:see_other | 303 |
:unauthorized | 401 |
:forbidden | 403 |
:not_found | 404 |
:method_not_allowed | 405 |
:internal_server_error | 500 |
Use
head :not_found
XML/JSON
XML
def res_xml @items = Item.all render xml: @item end
xml option
to_xml convert model to XML
Content-Type application/xml
JSON
def res_json @items = Item.all render json: @items end