1.GET
请求,返回一个对象
GET http://localhost:3000/api/v1/trains/0822
返回结果
{
"number": "0822",
"available_seats": [
"1A",
"1B",
"1C",
"2A",
"2B",
"2C",
"3A",
"3B",
"3C",
"4A",
"4B",
"4C",
"5A",
"5B",
"5C",
"6A",
"6B",
"6C"
]
}
render
的做法
app/controllers/api/v1/trains_controller.rb
def show
@train = Train.find_by_number!( params[:train_number] )
render :json => {
:number => @train.number,
:available_seats => @train.available_seats
}
end
jbuilder
的做法
app/views/api/v1/trains/show.json.jbuilder
json.number @train.number
json.available_seats @train.available_seats
json.created_at @train.created_at
2.GET
请求,返回一个数组
GET http://localhost:3000/api/v1/trains
返回结果
{
"data": [
{
"number": "0822",
"train_url": "http://localhost:3000/api/v1/trains/0822"
},
{
"number": "0603",
"train_url": "http://localhost:3000/api/v1/trains/0603"
},
{
"number": "0826",
"train_url": "http://localhost:3000/api/v1/trains/0826"
},
{
"number": "0642",
"train_url": "http://localhost:3000/api/v1/trains/0642"
}
]
}
render
的做法
app/controllers/api/v1/trains_controller.rb
def index
@trains = Train.all
render :json => {
:data => @trains.map{ |train|
{ :number => train.number,
:train_url => api_v1_train_url(train.number)
}
}
}
end
jbuilder
的做法
json.data do
json.array! @trains do |train|
json.number train.number
json.train_url api_v1_train_url(train.number)
end
end
3.使用partial
样板
子项目
app/views/api/v1/trains/_item.json.jbuilder
json.number train.number
json.available_seats train.available_seats
json.created_at train.created_at
修改1
app/views/api/v1/trains/show.json.jbuilder
- json.number @train.number
- json.available_seats @train.available_seats
- json.created_at @train.created_at
+ json.partial! 'item', train: @train
修改2
app/views/api/v1/trains/index.json.jbuilder
json.data do
- json.array! @trains do |train|
- json.number train.number
- json.train_url api_v1_train_url(train.number)
- end
+ json.array! @trains, :partial => "item", :as => :train
end
分页
库
Gemfile
gem 'will_paginate'
$ bundle install
app/controllers/api/v1/trains_controller.rb
def index
- @trains = Train.all
+ @trains = Train.paginate( :page => params[:page] )
end
app/views/api/v1/trains/index.json.jbuilder
+ json.meta do
+ json.current_page @trains.current_page
+ json.total_pages @trains.total_pages
+ json.per_page @trains.per_page
+ json.total_entries @trains.total_entries
+ if @trains.current_page == @trains.total_pages
+ json.next_url nil # 最后一页就没有下一页了
+ else
+ json.next_url api_v1_trains_url( :page => @trains.next_page )
+ end
+ if @trains.current_page == 1
+ json.previous_url nil # 第一页就没有上一页
+ else
+ json.previous_url api_v1_trains_url( :page => @trains.previous_page )
+ end
+ end
json.data do
json.array! @trains, :partial => "item", :as => :train
end
模拟数据
$ rails c
> 100.times { |i| Train.create( :number => "T#{i}" ) }