Makes it easy to list attributes that shouldn’t be serialized by to_xml and friends.
First, use the writer attr_visible
to list attributes that shouldn’t be shown to the world. Second, call serialize_defaults
with +:only => visible_attributes+. You may also list associations that you’d like to include, or any other argument accepted by the ActiveRecord::Serialization methods
You can only whitelist attributes.
Nothing enforces these attributes to be hidden in general. You should use serialize_defaults to create a whitelist of attributes, and in your views you can use visible_attributes
to check whether fields are listed as visible.
class User has_many :roles has_many :posts # User has attributes name, email, password; and has_many roles. # A user should to be able to modify her name and email, but not roles. attr_accessible :name, :email, :password, :password_confirmation # Let to_xml, to_json, etc show a user's id, name, roles and date they # joined, but don't show their email or password visible to the world. attr_visible :id, :name, :roles, :created_at # Additionally show how many posts they've made serialize_defaults :only => visible_attributes, :methods => :num_posts # number of posts by this user def num_posts posts.count end end
Then we would get
user = User.new("name" => "David", "email" => "foo@bar.com", "password" => "monkey", ... ) user.to_json # {"user": { "id":1, "name":"David", "email":"foo@bar.com", :created_at => '...', :num_posts => 0 } }
Copyright © 2008 Philip (flip) Kromer for infochimps.org Released under the MIT license