0

I currently have a JSON response, fairly simple one. But I couldn't find a good guide or kicking off point for getting the JSON response and saving it within a model that I have e.g posts.

"Grab a JSON feed containing posts and save each one within the posts table in rails"

Is there a simple way to do this with rails?

Any help is greatly appreciated.

Jonathan
  • 673
  • 1
  • 10
  • 32
  • Not a detailed answer but you'd iterated over the parsed JSON and save each field manually into a Post object. In pseudo code it's like post.name = JSON.name and so on before calling post.save before a loop completes. –  Mar 26 '16 at 01:44
  • Have you seen any tutorial explaining in more detail or care to write a small one below? :) – Jonathan Mar 26 '16 at 01:52
  • I've only access to my iPhone at the moment. Found this link. See the answer. Instead of site.short_url it's post.title or however you've formatted your JSON to look like. http://stackoverflow.com/questions/1826727/how-do-i-parse-json-with-ruby-on-rails –  Mar 26 '16 at 01:56

1 Answers1

1

Not a lot to work with...but let's assume the json string is represented by the variable json_str.

parsed = JSON.parse(json_str)

The parsed string should now essentially just be key value pairs like any other hash. To get the value, simply use the key.

parsed["some_key"]

Will return the value. To make your post from this, you can take the values you need and pass them in one by one, like so:

Post.create(some_value: parsed["some_key"], # etc)

Or, if all of your keys happen to share names with your attributes, you can pass the params all at once by saying:

post = Post.new(parsed)

and then calling:

post.save

Let me know if you have trouble.

toddmetheny
  • 4,405
  • 1
  • 22
  • 39
  • Hi Todd, thanks for giving me this answer. Understand it's not much to work with but just wanted a basic understanding of how to do this. Do you know a link to a full tutorial showing you how to do this from start to finish? – Jonathan Mar 26 '16 at 11:49