Ruby on rails 向上添加自定义属性

Ruby on rails 向上添加自定义属性,ruby-on-rails,json,serialization,Ruby On Rails,Json,Serialization,在使用时,我逐渐意识到它在阵列方面并没有像我预期的那样工作 因此,给定一个@posts数组(如自述文件所示),调用@posts.to_json既不包含用户也不显示标题 不确定这是否是预期的行为,或者我遗漏了什么,因为我找不到任何相关的东西 使用Rails 3.0.4 PS.在模型的JSON格式中包含2个自定义属性时,是否有其他选择?请考虑这样的重载: class Post def as_json(options) # make sure options is not nil

在使用时,我逐渐意识到它在阵列方面并没有像我预期的那样工作

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

不确定这是否是预期的行为,或者我遗漏了什么,因为我找不到任何相关的东西

使用Rails 3.0.4

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

请考虑这样的重载:

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

你能更清楚地阐述一下你想要实现什么吗?只显示title
@post.to_json(:only=>:title)
就可以了。要在json中包含用户,可以执行
@post.to_json(:include=>:user)