我正在使用 Sinatra 制作一个简单的小 API。我一直想不出如何从输出的JSON中删除 "password_digest "字段。好吧,我知道有一个很长的方法可以做到这一点,但我感觉有一个更简单的方法。
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
结束
我想做的就是把输出中的password_digest字段删除。有什么简单的方法可以做到这一点吗?我试着搜索了一下,没有找到。
get "/users/all" do
content_type :json
@users = User.all
@users.to_json(except: [:password_digest])
end
你也可以覆盖 #as_json
来从序列化中完全删除该属性。
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
你应该可以做到这一点。
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