Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord : Hide column while returning object

Is there an out-of-the-box way to always hide/remove a column (say, User.password) while returning an ActiveRecord object?

like image 605
zakelfassi Avatar asked May 02 '13 16:05

zakelfassi


3 Answers

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.

like image 134
Zach Kemp Avatar answered Nov 14 '22 17:11

Zach Kemp


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

like image 25
fotanus Avatar answered Nov 14 '22 17:11

fotanus


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
like image 7
PinnyM Avatar answered Nov 14 '22 16:11

PinnyM