2011-04-12 175 views
2

在使用serialize_with_options时,我意识到它不像我期望的那样工作在数组中。在to_json上添加自定义属性

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

不知道这是预期的行为还是我错过了一些东西,因为我找不到任何相关的东西。

Using Rails 3.0.4

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

+0

能否请您详细阐述稍微清楚你想达到什么样的?对于只显示标题'@ post.to_json(:only =>:title)'应该这样做。为了将用户包含在json中,可以执行'@ post.to_json(:include =>:user)' – rubish 2011-04-12 16:46:19

回答

2

考虑超载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