Mark Shff
Mark Shff

Reputation: 13

Trying to save api data to my database, @headline not being populated for table

I'm trying to save news data for stocks from an api to my "Headline" database. But I think my controller params are wrong and so I can't populate an item to save to my table.

I've tried changing the @headline = Headline.new_from_lookup(params[:stock]) params to :ticker :symbol but nothing changes. Still getting undefined method `save' for nil:NilClass

Routes.rb

Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes".

root 'headlines#new'

resources :headlines

end

headline.rb

class Headline < ActiveRecord::Base require 'iex-ruby-client'

def self.new_from_lookup(symbol)
    begin
    looked_up_stock = IEX::Resources::Quote.get(symbol)
    looked_up_news = IEX::Resources::News.get(symbol)
    new(ticker: looked_up_stock.symbol, name: looked_up_stock.companyName, headline: looked_up_news.first.headline, summary: looked_up_news.first.summary, url: looked_up_news.first.url)
    rescue Exception => e
        return nil
    end
end

end

headline_controller.rb

class HeadlinesController < ApplicationController

def new
    @headline = Headline.new
end

def create
 # takes input from the search page then finds the stock info with the model headline.rb
    @headline = Headline.new_from_lookup(params[:symbol])

    @headline.save # saves the headline info to the database

    redirect_to headline_path(@headline) # directs the user to the show path
end

def show
    @headline = Headline.find(params[:id]) # shows the news from the database that was just entered
end

end

new.html.erb

    <h1>Choose Stock News</h1>

        <%= form_for @headline do |f| %>
            <p>
                <%= f.label :ticker %>
                <%= f.text_field :ticker %>
            </p>
            <p>
                <%= f.submit %>
            </p>

        <% end %>



</body>

show.html.erb

Showing Selected Stock News

Ticker:

Name:

Headline:

Summary:

Url:

Created:

Updated:

Upvotes: 0

Views: 48

Answers (1)

Igor Kasyanchuk
Igor Kasyanchuk

Reputation: 774

Instead of

rescue Exception => e
        return nil
    end

write

rescue Exception => e
        puts e.message
        puts e.stacktrace.join("\n")
        return nil
    end

at least you can see what error you have

plus in controller you need to check later if object is nil

Upvotes: 0

Related Questions