jsonrubysinatrasinatra-activerecord

Removing password_digest from API json?


I'm using Sinatra to make a simple little API. I have not been able to figure out a way to remove the 'password_digest' field from the JSON I'm outputting. Well, I know of a long way that I can do it, but I have a feeling there is a much simpler way.

get "/users/all" do
content_type :json
@users = User.all

response = @users.map do |user|
  user = user.to_h  
  user.delete("password_digest")
  user
end
response.to_json

end

All I'm trying to do is remove the password_digest field from the output. Is there a simple way to do this? I've tried searching with no luck.

enter image description here


Solution

  • get "/users/all" do
      content_type :json
      @users = User.all
      @users.to_json(except: [:password_digest])
    end
    

    You can also overide #as_json on the model to remove the attribute completely from serialization:

    class User < ActiveRecord::Base
      def as_json(**options)
        # this coerces the option into an array and merges the passed
        # values with defaults
        excluding = [options[:exclude]].flatten
                                       .compact
                                       .union([:password_digest])
        super(options.merge(exclude: excluding))
      end
    end