Is there an out-of-the-box way to always hide/remove a column (say, User.password) while returning an ActiveRecord object?
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
.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With