构建API服务器3

分页

建立Micropost模型

$ rails g model Micropost

migration修改

class CreateMicroposts < ActiveRecord::Migration
  def change
    create_table :microposts do |t|
      t.string :title
      t.text :content
      t.integer :user_id
      t.timestamps null: false
    end
  end
end

执行:

rake db:migrate

为id为1的用户创建100条微博记录:
lib/tasks/data.rake

namespace :data do
  task :create_microposts => [:environment] do
    user = User.find(1)
    100.times do |i|
      Micropost.create(user_id :user.id, title: "title-#{i}", content: "content-#{i}")
    end
  end
end

执行:

$ rake data:create_microposts

新建Micropost的controller

rails g controller api/v1/microposts --no-assets

配置路由

namespace :api do
  namespace :v1 do
+   scope path: '/user/:user_id' do
+    resources :microposts, only: [:index]
+   end
end

此时路由为

api_v1_microposts GET /api/v1/user/:user_id/microposts(.:format) api/v1/microposts#index

安装kaminari

gem 'kaminari'

更改user Model

class User < ActiveRecord::Base
 + has_many :microposts
end

更改Microposts Controller

class Api::V1::MicropostsController < Api::V1::BaseController
+ def index
+ user = User.find(params[:user_id])
+ @microposts = paginate(user.microposts)
+ end
end

实现paginate函数

class Api::V1::BaseController < ApplicationController
  def paginate(resource)
    resource = resource.page(params[:page] || 1)
    if params[:per_page]
      resource = resource.per(params[:per_page])
    end
    return resource
  end
end

实现Helper方法

module ApplicationHelper
+ def paginate_meta_attributes(json, object)
+   json.(object,
+     :current_page,
+     :next_page,
+     :prev_page,
+     :total_pages,
+     :total_count)
+   end
end

修改app/api/v1/microposts/index.json.jbuilder

json.paginate_meta do
  paginate_meta_attributes(json, @mircoposts)
end
json.microposts do
  json.array! @microposts do |micropost|
    json.(micropost, :id, :title, :content)
  end
end

你可能感兴趣的:(构建API服务器3)