开发者

Adding custom attributes on to_json

开发者 https://www.devze.com 2023-02-25 13:52 出处:网络
While using serialize_with_options I came to realise that it doesn\'t work as I expected when it comes to arrays.

While using serialize_with_options I came to realise that it doesn't work as I expected when it comes to arrays.

So given an array of @posts (as seen in the README) calling @posts.to_json will neither include the user or show only the title.

Not sure if that's the expected behaviour or I'm missing something since I can't find 开发者_运维知识库anything related.

Using Rails 3.0.4

PS. Are there any alternatives when it comes to include 2 custom attributes on the JSON format of a model?


consider overloading ActiveModel::Serializers::JSON.as_json like that:

class Post
  def as_json(options)
    # make sure options is not nil
    options ||= {}
    # call super with modified options
    super options.deep_merge(methods: [:custom_attr1, :custom_attr2])
  end

  def custom_attr1
    "return first custom data"
  end

  def custom_attr2
    "return second custom data"
  end
end

#rspec this like that
describe Post do
  subject { Post.new }
  it "has custom data" do
    to_json.should include(
      { custom_attr1: "return first custom data",
        custom_attr2: "return second custom data"})
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消