Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Hides given attributes from serialization (to_xml, to_json, etc) by default.
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
rdoc
MIT-LICENSE
README.rdoc
Rakefile
init.rb

README.rdoc

AttrVisible

Description

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.

!! Please be aware !!

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.

Example

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

Something went wrong with that request. Please try again.