2012-02-19 10 views
1

私は私のレールアプリでacts_as_taggable_onを使用しています。私はこれらのタグを私のモデルのto_json表現に表示したいと思います。モデルのto_json出力にacts_as_taggable_onタグを含める

例えば、私のモデルの1つのインスタンスのto_jsonをは次のようになります。

{"created_at":"2012-02-19T03:28:26Z", 
"description":"Please!", 
"id":7, 
"points":50, 
"title":"Retweet this message to your 500+ followers", 
"updated_at":"2012-02-19T03:28:26Z"} 

...と私はそれがこのような何かを見てみたい:

{"created_at":"2012-02-19T03:28:26Z", 
"description":"Please!", 
"id":7, 
"points":50, 
"title":"Retweet this message to your 500+ followers", 
"updated_at":"2012-02-19T03:28:26Z" 
"tags" : 
    {"id":1, 
     "name":"retweet"}, 
    {"id":2, 
     "name":"twitter"}, 
    {"id":3, 
     "name":"social"} 
} 

私のコントローラコードを足場が私に与えるデフォルトです:

def show 
    @favor = Favor.find(params[:id]) 

    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @favor } 
    end 
end 

私はすでにテンプレート内の@ favor.tagsにアクセスできます。 @ favor.tags.to_jsonは期待通りに動作しますが、@ favor.to_jsonを出力するときにそのデータをインクルードする必要がありました。

答えて

3

to_jsonを呼び出すことで、json呼び出しにオプションを渡すことができます。または、あなたの好意モデルでas_jsonを再定義します。あなたの好意モデルオーバーライドas_json方法で

render json: @favor.to_json(include: :tags)

2

def as_json(options={}) 
    super(:include => :tags) 
end 
関連する問題