可以用三種方式讓瀏覽器讀取URL顯示JSON
下面這種是撈取member這個table所有資料
http://localhost:3000/api/member
下面這種是撈取member的第一筆資料,如果要撈第50筆資料把數字改成50就好
http://localhost:3000/api/member/1
...
http://localhost:3000/api/member/50
下面這種跟http://localhost:3000/api/member/1 一樣都是撈第一筆資料只是URL寫法不同而已
http://localhost:3000/api/member/1.json
Model:
$rails g model member name:string email:string
Controller:
$rails g controller /api member
member_controller.rb
def index
@member = Member.all
render json: @member
end
def show
@member = Member.find(params[:id])
render json: @member
end
def create
@member = Member.new()
if @member.save
render json: @member
else
render json: @member.errors, status: :unprocessable_entity
end
end
def update
if
@member.update()
render json: @member
else
render json: @member.errors, status: :unprocessable_entity
end
end
def destroy
@member.destroy
head :no_content
end
Routes:
namespace :api do
resource :members, only: [:index, :create, :show, :update, :destroy]
end
查詢資料
curl -i http://localhost:3000/api/member/
寫入資料
curl -i -X POST -H "Content-Type: application/json" -d '{"member": {"name":"Apple","email':"ABC@gmail.com"}}' http://localhost:3000/api/member
更新指定資料
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Apple","email':"ABC@gmail.com"}}' http://localhost:3000/api/member/1
刪除指定資料
curl -i -X DELETE http://localhost:3000/api/member/1