代码之家  ›  专栏  ›  技术社区  ›  coneybeare

如何定制rails3中的json响应

  •  16
  • coneybeare  · 技术社区  · 15 年前

    respond_with json , xml foobar 格式,但我不知道如何使用有限的 :only :include . 当数据很简单时,这些都是很好的,但是对于复杂的发现,它们没有达到我想要的。

    has_many 图像

    def show
      @post = Post.find params[:id]
      respond_with(@post)
    end
    

    def show
      @post = Post.find params[:id]
      respond_with(@post, :include => :images)
    end
    

    但是我真的不想发送整个图像对象,只是url。除此之外,我真的希望也能做类似的事情(伪代码):

    def show
      @post = Post.find params[:id]
      respond_with(@post, :include => { :foo => @posts.each.really_cool_method } )
    end
    
    def index
      @post = Post.find params[:id]
      respond_with(@post, :include => { :foo => @post.really_cool_method } )
    end
    

    但都是干的。在旧的rails项目中,我使用了XML构建器来定制输出,但是在json、XML、html中复制输出似乎并不正确。我不得不想象rails大师在Rails3中加入了一些我没有意识到的行为。思想?

    3 回复  |  直到 15 年前
        1
  •  21
  •   PerfectlyNormal    14 年前

    您可以覆盖 as_json 在你的模型里。

    class Post < ActiveRecord::Base
      def as_json(options = {})
        {
          attribute: self.attribute, # and so on for all you want to include
          images:    self.images,    # then do the same `as_json` method for Image
          foo:       self.really_cool_method
        }
      end
    end
    

    使用时,Rails会处理其余部分 respond_with . 不完全确定什么 options 设置为,但可能是您给 用…回应 ( :include , :only

        2
  •  8
  •   Nerdmaster    14 年前

    可能太迟了,但我找到了一个更干燥的解决办法。这在我的简短测试中有效,但可能需要一些调整:

    # This method overrides the default by forcing an :only option to be limited to entries in our
    # PUBLIC_FIELDS list
    def serializable_hash(options = nil)
      options ||= {}
      options[:only] ||= []
      options[:only] += PUBLIC_FIELDS
      options[:only].uniq!
      super(options)
    end
    

        3
  •  7
  •   Matt Huggins    14 年前

    这不是rails 3的内置方式,但我发现rails 3上有一个非常好的宝石: acts_as_api