Search code examples
ruby-on-railsrubydatabaseblogsfield

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?


Solution

  • 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