【问题标题】:Adding custom attributes on to_json在 to_json 上添加自定义属性
【发布时间】:2011-08-03 23:55:09
【问题描述】:

在使用serialize_with_options 时,我意识到它在数组方面并没有像我预期的那样工作。

因此,给定一个@posts 数组(如自述文件中所示),调用@posts.to_json 既不会包含用户,也不会只显示标题。

不确定这是否是预期的行为,或者由于找不到任何相关内容,所以我遗漏了一些东西。

使用 Rails 3.0.4

PS。在模型的 JSON 格式中包含 2 个自定义属性时,是否有其他选择?

【问题讨论】:

  • 你能详细说明一下你想要达到什么目的吗?只显示标题@post.to_json(:only => :title) 应该可以解决问题。要将用户包含在 json 中,您可以执行 @post.to_json(:include => :user)

标签: ruby-on-rails json serialization


【解决方案1】:

考虑像这样重载ActiveModel::Serializers::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

【讨论】:

    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多