【问题标题】:render :json does not accept optionsrender :json 不接受选项
【发布时间】:2010-10-11 08:20:56
【问题描述】:

我很想使用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

【问题讨论】:

    标签: ruby-on-rails json api


    【解决方案1】:

    我对@9​​87654321@ 做了类似的事情。这对我有用:

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

    【讨论】:

    • 谢谢,这也帮助了我。
    【解决方案2】:

    我想这篇文章可能对你有用 - Rails to_json or as_json? Jonathan Julian。

    主要的想法是你应该避免在控制器中使用 to_json。在模型中定义 as_json 方法更加灵活。

    例如:

    在你的事物模型中

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

    然后你就可以在你的控制器中写代码了

    render :json => @things
    

    【讨论】:

    • 可能想要做super(options.merge(:include => :photos)) 以保留其他可能的传入选项。您仍然可以覆盖任何 :include 选项,但是......合并该键的值的逻辑会涉及更多。
    • 使用super options.reverse_merge :include => :photos 将允许您覆盖“默认”:include。 (见Hash#reverse_merge
    【解决方案3】:

    在你的控制器中管理复杂的哈希值很快就会变得很丑。

    在 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
    

    【讨论】:

      【解决方案4】:
      format.json { render @things.to_json(:include => :photos) }
      

      【讨论】:

        【解决方案5】:

        如果是数组,我所做的是

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

        【讨论】:

          猜你喜欢
          • 2018-05-02
          • 2023-03-31
          • 1970-01-01
          • 2019-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多