Rails中对象的序列化包括两个步骤:
- 首先,
as_json
调用将对象转换为简化的Hash。 - 然后,
to_json
在as_json
返回值上调用,以获取最终的JSON字符串。
通常,您希望
to_json一个人呆着,因此您所要做的就是添加自己的
as_json实现,如下所示:
def as_json(options = { }) # just in case someone says as_json(nil) and bypasses # our default... super((options || { }).merge({ :methods => [:finished_items, :unfinished_items] }))end您也可以这样:
def as_json(options = { }) h = super(options) h[:finished] = finished_items h[:unfinished] = unfinished_items hend如果要为方法支持的值使用不同的名称。
如果您关心XML和JSON,请参阅
serializable_hash。



