문제

내가 사랑하는 사용 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 메소드를 정의하는 것이 훨씬 유연합니다.

예를 들어:

당신의 사물 모델에서

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

그런 다음 컨트롤러에만 쓸 수 있습니다

render :json => @things

를 관리하는 복잡한 해시 컨트롤러에서 얻을 추한 빠르다.

레일 3 를 사용할 수 있습 ActiveModel::Serializer.보 http://api.rubyonrails.org/classes/ActiveModel/Serialization.html

당신은 아무것도 아닌 사소한 참조하십시오 https://github.com/rails-api/active_model_serializers.추천을 만드는 별도의 serializer 클래스의 혼란을 방지하기 위해 귀하의 모델 테스트 쉽습니다.

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