(Rails3.2.13)
- http://railscasts.com/episodes/320-jbuilder?language=ja&view=asciicast
- https://github.com/rails/jbuilder
下準備
$ rails new jbuilder_app -T --skip-bundle $ cd jbuilder_app $ bundle install $ rails generate scaffold Book title price:integer $ rake db:migrate
db/seed.rb
Book.create(title: "明暗", price: 788) Book.create(title: "草枕", price: 452)
$ rake db:seed
json出力確認
{"created_at":"2013-05-19T09:14:48Z","id":1,"price":788,"title":"明暗","updated_at":"2013-05-19T09:14:48Z"}
jbuilderを使ってみる
app/controllers/books_controller.rb
respond_to を削除
def show @book = Book.find(params[:id]) end
Json を Javascript(coffeescript) を使って表示してみる
app/views/books/show.html.erb
: <hr /> <%= link_to "show json", "#", id: "show_json_btn" %> <div id="show_json"></div>
app/assets/javascripts/books.js.coffee
$ -> $json_content = $('#show_json') $(document).on 'click', '#show_json_btn', (e) -> e.preventDefault() $.getJSON location.pathname + ".json", (book)-> $json_content.html('') $json_content.append(book.title + ": " + book.price + "yen<br />") $json_content.append("<a href='#{book.index_path}'>Books</a>" + "<br />") $json_content.append(JSON.stringify(book))
click button "show json"