私は私のレールアプリで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を出力するときにそのデータをインクルードする必要がありました。