如果您遵循 Bart Jedrocha 的建议并使用 jbuilder(它是默认添加的),那么这两个respond_*
方法调用都变得不必要了。这是我为测试 Android 应用程序而制作的一个简单 API。
# 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