いつもよくわからなくなって混乱するので調べてまとめた。実験に使ったアプリ https://github.com/kyanny/backbone_sync_rails_app
フロントエンドを Backbone.js、バックエンドを Rails として、 fetch/save/destroy いずれの場合も必ず token
というパラメータを付与したい場合、それぞれ以下のようになる。
fetch (id なし)
fetch にパラメータをつけたい場合は data: {token: 'abc'}
の形でオプションを渡す。
user = new User
user.fetch
data:
token: 'abc'
GET http://localhost:3000/users?token=abc
Started GET "/users?token=abc" for 127.0.0.1 at 2014-12-08 22:51:31 +0900
Processing by UsersController#index as JSON
Parameters: {"token"=>"abc"}
""
Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)
fetch (id あり)
user = new User id: 123
user.fetch
data:
token: 'abc'
GET http://localhost:3000/users/123?token=abc
Started GET "/users/123?token=abc" for 127.0.0.1 at 2014-12-08 22:51:32 +0900
Processing by UsersController#show as JSON
Parameters: {"token"=>"abc", "id"=>"123"}
""
Completed 200 OK in 2ms (Views: 0.4ms | ActiveRecord: 0.0ms)
save (id なし)
save の場合は model の attributes が JSON になった文字列がリクエストボディになるので save の第一引数で渡す(もしくは model.set してもいい)
user = new User
user.save
token: 'abc'
POST http://localhost:3000/users
Started POST "/users" for 127.0.0.1 at 2014-12-08 22:51:33 +0900
Processing by UsersController#create as JSON
Parameters: {"token"=>"abc", "user"=>{"token"=>"abc"}}
"{\"token\":\"abc\"}"
Completed 201 Created in 2ms (Views: 0.5ms | ActiveRecord: 0.0ms)
save (id あり)
user = new User id: 123
user.save
token: 'abc'
PUT http://localhost:3000/users/123
Started PUT "/users/123" for 127.0.0.1 at 2014-12-08 22:51:34 +0900
Processing by UsersController#update as JSON
Parameters: {"id"=>"123", "token"=>"abc", "user"=>{"id"=>"123", "token"=>"abc"}}
"{\"id\":123,\"token\":\"abc\"}"
Completed 200 OK in 1ms (Views: 0.1ms | ActiveRecord: 0.0ms)
destroy
destroy の場合は model の attributes は送られないので data: {token: 'abc'}
の形でオプション渡しする必要がある。なおかつ processData: true
をつけないと [object object]
みたいな文字列がサーバーに送られてしまう。
user = new User id: 123
user.destroy
data:
token: 'abc'
processData: true
DELETE http://localhost:3000/users/123
Started DELETE "/users/123" for 127.0.0.1 at 2014-12-08 22:51:34 +0900
Processing by UsersController#destroy as JSON
Parameters: {"token"=>"abc", "id"=>"123"}
"token=abc"
Completed 204 No Content in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)