---
title: "关于json"
author: "夜鸣猪"
date: "2011-11-26T22:03:29Z"
tags: []
categories: ["编程语言"]
slug: "json"
draft: false
lastmod: "2011-11-26T22:03:29Z"
id: 1279071
url: "https://hlee.iteye.com/blog/1279071"
---

js.erb


```ruby


alert('New object id: ' + <%= @user.id %>);
```


在这个文件里读rails变量到js,实际是可以直接运行rails


标注一个render json需要include和only选择的

```ruby


respond_to do |format|
    format.html # index.html.erb
    format.json  { render :json => @things.to_json(:include => { :photos => { :only => [:id, :url] } }) }
end

```


这个有个比较cool的做法


```ruby

class Things < ActiveRecord::Base
  def as_json(options={})
    super(options || include: :photos, only: [:id, :url])#1.9 hash
  end
end

#然后controller就可以直接用
render :json => @things

```