nolyoly
nolyoly

Reputation: 136

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

Upvotes: 0

Views: 465

Answers (2)

Jocko
Jocko

Reputation: 537

You should be able to do this:

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

    response = @users.map do |user|
      user = user.to_h  # If your data is already a hash, you don't need this line.
      user.delete(:password_digest) # <-- If your keys are symbolized
      user.delete("password_digest") # <-- If your keys are strings
      user
    end
    response.to_json
  end

Upvotes: 0

max
max

Reputation: 101811

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

Upvotes: 1

Related Questions