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 アプリケーションプログラミング
- 作者: 山田祥寛
- 出版社/メーカー: 技術評論社
- 発売日: 2011/05/12
- メディア: 大型本
- 購入: 27人 クリック: 664回
- この商品を含むブログ (41件) を見る