我喜欢使用 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

管理控制器中的复杂哈希变得非常难看。

使用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