Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails render:json不接受选项_Ruby On Rails_Json_Api - Fatal编程技术网

Ruby on rails render:json不接受选项

Ruby on rails render:json不接受选项,ruby-on-rails,json,api,Ruby On Rails,Json,Api,我喜欢使用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

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

我想这篇文章可能对你有用——作者:乔纳森·朱利安

主要思想是,您应该避免在控制器中使用to_json。在模型中定义as_json方法要灵活得多

例如:

在你的事物模型中

def as_json(options={})
  super(:include => :photos)
end
然后你就可以在你的控制器里写东西了

render :json => @things

在数组的情况下,我所做的是

respond_to do |format|
  format.html
  format.json {render :json => {:medias => @medias.to_json, :total => 13000, :time => 0.0001 }}
end

在控制器中管理复杂的散列变得很快

对于Rails3,您可以使用ActiveModel::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
class ThingSerializer@things
结束
#试一试
thing=thing.new:name=>“bob”
ThingSerializer.new(thing,nil).to_json

谢谢,这也帮了我的忙。可能需要执行
super(options.merge(:include=>:photos))
以保留其他可能传入的选项。您仍然可以覆盖任何
:包括
选项,但是。。。合并该键的值的逻辑将更加复杂。使用
super options.reverse\u merge:include=>:photos
将允许您覆盖“默认值”:include。(见附件)
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