Rails how to: post json data with data in has_many relation / has_many の関係も含めて json データを post する

ちょっと詰まりました。これについて書かれたエントリーがあまりなかったのでメモを残しておきます。

Suppose there are two models "User" and "Book" in the following relation.
ユーザー(User)とその蔵書(Book)ふたつのモデルがあって、以下のような関係にあるとします。

User < ActiveRecord::Base
 has_many :books
Book < ActiveRecord::Base
 belongs_to :user

If you want to post and save a user data with his/her books data as json data, you should mind following points.
ユーザーの情報と共に本の情報も Rails アプリの API に post したいとします。気をつけなければいけない点は2つ。

  • Add "accepts_nested_attributes_for :books" to the User model. / Use モデルに「accepts_nested_attributes_for :books」を書き足す
  • In the json data, the data of books must be described "books_attributes: [ {title:"title 1", author:"author 1"}, ...]" not "books: [ {title:"title 1", author:"author 1"}, ...]". / 送信側の json データでは「books: [ {title:"title 1", author:"author 1"}, ...]」ではなくて「books_attributes: [ {title:"title 1", author:"author 1"}, ...]」と書く

Then, you'll successfully get the json data at the server side :)
これで無事データを受け取れるようになります。よかったよかった(^^)


Ruby on Rails 3 アプリケーションプログラミング

Ruby on Rails 3 アプリケーションプログラミング

# この本よさそう。Rails3対応、しかもAmazonのレビュー高評価!日本に帰った時にチェックしよう。