Search code examples
ruby-on-railsrubyhttparty

How to save HTTParty response to db?(Update!)


Need to save httparty response to db and call it in view file

this is what httrparty get

enter

in services folder/

 class ParserService
      include HTTParty
      API_KEY = '882e10dd2b474a23bb7a3efa85e66b61'.freeze
      base_uri 'https://newsapi.org/v2/'
      default_params fielsd: "title, description, ulr, content"
      format :json

      def self.top_headlines(country_name='us') 
        new(country_name).top_headlines
      end

      def initialize(country_name='us')
        @options = { query: { country: country_name, apiKey: API_KEY} }
      end

        def top_headlines 
          response = self.class.get("/top-headlines", @options)
          pars_json = response.parsed_response
          pars_json["articles"].each do |k|
            @source = ActiveModel::Source.create(google_id: k["id"], name: k["name"])

            @article = Article.create(title: k["title"], source_id: @source.id,
                                      description: k["description"], content: k["content"])

          end
        end  
    end

ArticleController

class ArticlesController < ApplicationController


    def index
        @articles = Article.all
    end
end

and model

class Article < ApplicationRecord
    belongs_to :source, class_name: "Source", optional: true
    validates :title, presence: true
    validates :source_id, uniqueness: true 

end

and schema.rb

enter image description here

That what I done now if try to save Article in (rails c) console have this error, validation

enter image description here

when try to comment validation it save but....it save empty fields

enter image description here

and I realy do not understand why it empy, when I call JSOn directlly, without saving to db, on view it show all what I need, but now I have this... on index page

enter image description here

enter image description here

and in console later got errors

enter image description here

I can image how to fix this and what and where go wrong


Solution

  • from what it looks like to me:

    pars_json.each do |k|
      art = ParserService.new('us')
      res = response.body
      art.title = res["title"]
      art.save
    end
    

    this piece is where you're trying to save it to the DB? I don't think ParserService is a model you've created that reflects a table from your DB.

    if you have the Article model that you're wanting to use to save each object parsed from API call you'd want to do something as such instead of the above:

    pars_json.each do |k|
      article = Article.create(title: k["title"], k["description"]...)
    end
    

    Try to first print out what k is exactly and line up the object keys to correspond to the correct Article fields.

    Again, to save to the DB, you need to use a model you've created that reflects a table on the DB. if you have the articles table on your DB where you'd like to save your API response data, then you should create instances of Article and save those.

    Then in the controller it's just calling it by @articles = Article.all or whichever query you'd like to run to have your list of articles.

    I'd recommend running the ParserService in a Background job to have the API fetch the data on a parallel process without having it affect too much the rails process