有没有办法从 json 设置对象的属性,忽略未知属性?

Is there a way to set attributes of an object from a json, ignoring unknown attributes?

实际上,我有这个:

      ip = HTTP.get("http://ip-api.com/json/24.48.0.1")
      if ip.code == 200
        Ipgeo.create(JSON.parse(ip.body).deep_symbolize_keys)
      end

我想从 http 请求的 json 响应创建 Ipgeo 对象。 http请求的属性比我的对象多,所以报错是:

ActiveModel::UnknownAttributeError: unknown attribute

有什么办法吗?就像使用参数创建以排除未知属性一样?或使用该对象的已知参数过滤我的 json?

我想跳过以下过程:

ip = Ipgeo.new()
ip.country = JSON.parse(ip.body)["country"]
ip.lat = JSON.parse(ip.body)["lat"]
...

Or

ip = Ipgeo.create(
  country: JSON.parse(ip.body)["country"]
...
)

column_names method in ActiveRecord it returns a list of column names (an array of strings) that a model contains. If you pass the result of this method to slice 您将仅获得您的模型所具有的属性。

Ipgeo.create(JSON.parse(ip.body).slice(*Ipgeo.column_names))

UPD

正如@max在评论中提到的,有白名单就好了。

IPGEO_ATTRIBUTES = ['country', 'lat']
#...
Ipgeo.create(JSON.parse(ip.body).slice(*IPGEO_ATTRIBUTES))