开发者

Rails: How to hide a model's attribute?

I got a Ruby model "Comment" with several attributes: username, date_added, modify_date, etc. When I c开发者_高级运维reate an instance of this model, call it "i", and call i.attributes, it gives me all the attributes for this model. Is there anyway to make it not return several attributes I want to keep private.

Reason being, I am lazily calling to_json for i.attributes, and some models contain sensitive information such as password, and I want to make these private.


Try using the :only or :except options for the #to_json method. For example:

@comment.to_json(:only => [ :username, :date_added, :modify_date ])

... or without hash rockets if you're on Ruby 1.9 ...

@comment.to_json(only: [ :username, :date_added, :modify_date ])


One idea is to "override" the to_json method in the models that have sensitive data


You could create a method such as Comments.public_attributes that only returns the attributes you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜