ActiveRecord : Hide column while returning object

Did you get to this page because you are trying to hide plain text passwords?

STOP! you are doing it wrong.

You should not, never, ever keep passwords in plain text.

Chances are that your server has or will have some kind of flaw and hackers will get your clients passwords. Think for a while:

  • What will you tell them?
  • How will they react?
  • What are the outcomes for your business?

Since you are now a new person and are searching about the correct way to store passwords, you might want to read this nice article


You can hide a specific attribute at serialization time using :except:

render json: @users, except: [:password, :other]

Alternatively, you can use after_initialize for this, and move the data into a non-serialized attribute:

class User < ActiveRecord::Base
  attr_accessor :hidden_password, :hidden_other
  after_initialize :hide_columns

  def hide_columns
    [:password, :other].each do |c|
      send("hidden_#{c}=", send(c))
      send("#{c}=", nil)
    end
  end
end

Using the built-in serialization, you can override the as_json method on your model to pass in additional default options:

class User < ActiveRecord::Base
  # ...
  def as_json(options = {})
    super(options.merge({ except: [:password, :oauth_token] }))
  end
end

There are probably better serialization tools out there - if you are looking for more fine-grained control I would recommend checking out active_model_serializers or rabl.