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

Time:04-19

Actual, I have this:

      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

I want to create the Ipgeo object from the json response of the http request. The http request has more attributes than my object, so the error raised is:

ActiveModel::UnknownAttributeError: unknown attribute

Is there a way that it works? Like create with a params for excluding unknown attributes? or filter my json with the know parameters for that object?

I want to skipt the process of:

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"]
...
)

CodePudding user response:

There is the column_names method in ActiveRecord it return a list of column names (an array of strings) that a model contains. If you pass the result of this method to slice you'll get only attributes that your model has.

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