--- layout: old_post title: scaffold_resourceでREST fullなRailsアプリ(1) permalink: /tatsuya/show/242-scaffold-resource-rest-full-rails-1 ---
Rails1.2から入ったscaffold_resourceを試してみる。まずごく単純に
ruby script/generate scaffold_resource Hoge title:string
titleフィールドのみを持つHogeリソースを作る、でrake migrateして完了!アクセスしてみる
irb(main):002:0* require 'net/http' irb(main):003:0> http = Net::HTTP.start('localhost',3000) irb(main):005:0> p http.get('/hoges.xml').body <?xml version="1.0" encoding="UTF-8"?> <nil-classes></nil-classes>
hogesにGETのアクセスでindex
irb(main):006:0> p http.post('/hoges.xml','hoge[title]=AAA').body " " => nil
hogesにPOSTのアクセスでnew (Create)
irb(main):007:0> p http.get('/hoges.xml').body <?xml version="1.0" encoding="UTF-8"?> <hoges> <hoge> <id type="integer">7</id> <title>AAA</title> </hoge> </hoges>
//確認
irb(main):008:0> p http.get('/hoges/7.xml').body <?xml version="1.0" encoding="UTF-8"?> <hoge> <id type="integer">7</id> <title>AAA</title> </hoge>
/hoges/:id にGETアクセスでshow (Read)
irb(main):009:0> p http.put('/hoges/7.xml','hoge[title]=BBB').body " " => nil
/hoges/:id にPUTアクセスでedit (Update)
irb(main):010:0> p http.get('/hoges/7.xml').body <hoge> <id type="integer">7</id> <title>BBB</title> </hoge>
確認
irb(main):011:0> p http.delete('/hoges/7.xml').body " " => nil
/hoges/:id にDELETEアクセスでdestroy (Delete)
irb(main):013:0> p http.get('/hoges.xml').body <?xml version="1.0" encoding="UTF-8"?> <nil-classes></nil-classes>
確認
本当にHTTPのPOST/GET/PUT/DELETEそれぞれの方式で、CRUDに対応させている。いまのwebではPUT/DELETE なんてメソッド実際に見たことはないけど、そのほうが美しいならそうしようって発想が凄い。scaffold_resource凄いね