日期:2014-05-16  浏览次数:20341 次

to_json 中增加自定义的属性字段

参考:http://stackoverflow.com/questions/5111165/accessing-virtual-attribute-from-json

?

原本我这样写:

@user.to_json(:only => [:id, :name, :pay_points])

?后来我想增加一个属性,它不是一个数据库字段,是在@user中定义的一个方法:

def points_value
    ......
    
end

?

我将to_json输出改成了:

@user.to_json(:only => [:id, :name, :pay_points, :points_value])

但结果没有输出points_value.

?

?

正确的做法是:

@user.to_json(:only => [:id, :name, :pay_points],:methods => :points_value)
?