gpt4 book ai didi

ruby-on-rails - 在 Ruby on Rails 中隐藏字段

转载 作者:数据小太阳 更新时间:2023-10-29 07:03:35 27 4
gpt4 key购买 nike

我的数据库中有一个名为 IP 的字段,当他在我的 Rails 内置博客中发送消息时,我将用户 IP(在 #create 方法中)放在该字段中。

但是当我想以另一种格式(JSON)查看文章时,该字段是可见的。如何隐藏字段IP?

最佳答案

您可以在 Controller 中的格式 block 中执行此操作,如下所示:

respond_to do |format|
format.json { render :json => @user, :except=> [:ip] } # or without format block: @user.to_json(:except => :ip)
end

如果你想普遍排除特定字段,只需覆盖用户模型中的 to_json 方法即可:

class User < ActiveRecord::Base
def to_json(options={})
options[:except] ||= [:ip]
super(options)
end
end

更新:在Rails 6中,方法变成了as_json:

class User < ApplicationRecord
def as_json(options={})
options[:except] ||= [:ip]
super(options)
end
end

关于ruby-on-rails - 在 Ruby on Rails 中隐藏字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10431741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com