Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide a field in Ruby on Rails

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?

like image 592
Roxas Shadow Avatar asked May 03 '12 12:05

Roxas Shadow


2 Answers

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
like image 161
emrass Avatar answered Nov 04 '22 08:11

emrass


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

like image 5
jrochkind Avatar answered Nov 04 '22 08:11

jrochkind