Rails3でhas_manyなmodelをjsonで返したいときー
ここ嫁
http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
つまり、これがツイッター風なデータモデルだったとして、Userと一緒にUserのTweetがネストされたJsonデータを返したいとなるとmodelが
class User < ActiveRecord::Base 〜 snip 〜 has_many :tweets, :dependent => :destroy end
的な感じでcontroller
class HogeController < ApplicationController respond_to :json, :only => [:show] def show @user = User.find(param[:id]) if request.xhr? respond_with @user.as_json(:include => :tweets) end end end
的な感じかな!