Elsie Hamilton
Elsie Hamilton

Reputation: 155

How can I store a Json responce in database in ruby on rails

How can I store the json response which I am getting form api into my database. Here is what I want to do the responce from API:

[
  {
    "tag_id": "1",
    "tag_name": "FCC",
    "group_id": "15",
    "object_type_id": "0"
  },
  {
    "tag_id": "2",
    "tag_name": "SWA Buyers",
    "group_id": "15",
    "object_type_id": "0"
  },
  {
    "tag_id": "3",
    "tag_name": "SWA Nonbuyers",
    "group_id": "15",
    "object_type_id": "0"
  }
]

Now I want to store all the info in my table

Upvotes: 0

Views: 77

Answers (2)

huyhoang-vn
huyhoang-vn

Reputation: 335

You can do it as:

  • You add a column to table which you want save that data example "info" column to students table which is text type
  • In Student model, you add this line:

    serialize :info, Hash
    

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

You have plenty of options here.

  1. Store this JSON as a string (in a text column). This obviously won't let you do any queries against the data. You can only read it as a whole.

  2. Parse the response and create individual Tag records in your database.

  3. If your database supports it (postgresql, for example), store it in special json column. This is a middle of the previous two options: you get some querying capabilities and ease of saving.

Upvotes: 1

Related Questions