Content negotiation cho phép một action phản hồi theo format khác nhau (HTML, JSON, XML) tùy Accept header hoặc URL extension.
ruby
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # render app/views/posts/show.html.erb
format.json { render json: @post }
format.xml { render xml: @post }
end
end
endRequest GET /posts/1 → HTML. GET /posts/1.json hoặc header Accept: application/json → JSON.
respond_with (từ gem responders) ngắn gọn hơn cho CRUD chuẩn nhưng ít tùy biến hơn. Với Rails API mode (ActionController::API), response mặc định là JSON và không cần respond_to.