在to_json上添加自定义属性

时间:2022-12-08 23:21:14

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

在使用serialize_with_options时,我意识到它不能像我预期的那样在数组中工作。

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.

所以给定一个@posts数组(如README中所示)调用@posts。to_json既不包含用户也不显示标题。

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

使用Rails 3.0.4

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

当涉及到一个模型的JSON格式的两个自定义属性时,是否还有其他选择?

1 个解决方案

#1


2  

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

考虑重载ActiveModel::序列化器::JSON。as_json像这样:

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

#1


2  

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

考虑重载ActiveModel::序列化器::JSON。as_json像这样:

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