9

I've a field in my database called IP where I put the user IP (in #create method) when he send a message in my blog built in Rails.

But the field is visible when I want to see the articles in another format (JSON). How can I hide the field IP?

Matt
  • 74,352
  • 26
  • 153
  • 180
Roxas Shadow
  • 380
  • 4
  • 8

2 Answers2

14

You can do it in a format block in your controller like this:

respond_to do |format|
  format.json { render :json => @user, :except=> [:ip] } # or without format block: @user.to_json(:except => :ip)
end

If you want to generally exclude specific fields, just overwrite the to_json method in your user model:

class User < ActiveRecord::Base
  def to_json(options={})
    options[:except] ||= [:ip]
    super(options)
  end
end

Update: In Rails 6, the method became as_json:

class User < ApplicationRecord
  def as_json(options={})
    options[:except] ||= [:ip]
    super(options)
  end
end
emrass
  • 6,253
  • 3
  • 35
  • 57
  • So if I exclude [:ip] from json I can be sure that nobody can see it? – Roxas Shadow May 03 '12 at 13:49
  • Yes, :except means that it completely skips writing that property into the JSON output. – Nate May 03 '12 at 13:59
  • Using except makes sure that the given attribute(s) is/are not included in the json encoding. So if you define "nobody" as the set of users who see the json representation, then yes. The field will still be there on the DB, so a database admin will be able to see it. – emrass May 03 '12 at 13:59
  • Please note that if you are using `to_json` you are doing it wrong: http://blog.codepath.com/2011/05/16/if-youre-using-to_json-youre-doing-it-wrong/ and https://quickleft.com/blog/keeping-your-json-response-lean-in-rails/ – tread May 11 '15 at 10:11
5

While this is not quite the right solution for passwords or for what is specifically asked, this is what comes up when you google for hiding columns in ActiveRecord, so I'm going to put this here.

Rails5 introduced new API, ignored_columns, that can make activerecord ignore that a column exists entirely. Which is what I actually wanted, and many others arriving here via Google probably do too.

I haven't tried it yet myself.

class User < ApplicationRecord
  self.ignored_columns = %w(employee_email)
end

https://blog.bigbinary.com/2016/05/24/rails-5-adds-active-record-ignored-columns.html

jrochkind
  • 22,799
  • 12
  • 59
  • 74