質問

render:json を使用したいのですが、それほど柔軟ではないようです。これを行う正しい方法は何ですか?

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @things }

  #This is great
  format.json { render :text => @things.to_json(:include => :photos) }

  #This doesn't include photos
  format.json { render :json => @things, :include => :photos }
end
役に立ちましたか?

解決

render:json で同様のことを行いました。これは私のために働いたものです:

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

他のヒント

この記事は役に立つと思います- Rails to_jsonまたはas_json?ジョナサン・ジュリアン。

主な考えは、コントローラーでto_jsonを使用しないようにすることです。モデルでas_jsonメソッドを定義する方がはるかに柔軟です。

たとえば:

Thingモデルで

def as_json(options={})
  super(:include => :photos)
end

そして、コントローラーに書き込むことができます

render :json => @things

コントローラーでの複雑なハッシュの管理はい高速になります。

Rails 3では、ActiveModel :: Serializerを使用できます。 http://api.rubyonrails.org/classes/ActiveModel/Serialization.html

自明ではないことをしている場合は、 https://github.com/rails-api/active_model_serializers 。モデルが乱雑にならず、テストが簡単になるように、個別のシリアライザークラスを作成することをお勧めします。

class ThingSerializer < ActiveModel::Serializer
  has_many :photos
  attributes :name, :whatever
end

# ThingsController
def index
  render :json => @things
end

# test it out
thing = Thing.new :name => "bob"
ThingSerializer.new(thing, nil).to_json
format.json { render @things.to_json(:include => :photos) }

配列の場合、私がしたことは

respond_to do |format|
  format.html
  format.json {render :json => {:medias => @medias.to_json, :total => 13000, :time => 0.0001 }}
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top