If you follow Bart Jedrocha's suggestion and use jbuilder (it's added by default), then both the respond_*
method calls become unnecessary. Here's a simple API I made to test an Android app.
# controllers/api/posts_controller.rb
module Api
class PostsController < ApplicationController
protect_from_forgery with: :null_session
def index
@posts = Post.where(query_params)
.page(page_params[:page])
.per(page_params[:page_size])
end
private
def page_params
params.permit(:page, :page_size)
end
def query_params
params.permit(:post_id, :title, :image_url)
end
end
end
# routes.rb
namespace :api , defaults: { format: :json } do
resources :posts
end
# views/api/posts/index.json.jbuilder
json.array!(@posts) do |post|
json.id post.id
json.title post.title
json.image_url post.image_url
end