2017-12-29 5 views
0

저는 Rails 초보자이고 Udemy의 Rails 개발자 과정을 완료하고 있습니다. /search_stocks 경로로 이동하려고하면 다음 오류가 발생합니다. https://github.com/sarahbasinger/rails-stock-trackerRuby on Rails - 정의되지 않은 메서드 인 'split'for nil : StocksController # search의 NilClass/NoMethodError

여기 Udemy 코스의 repo의 : 이 https://github.com/udemyrailscourse/finance-tracker

과정에 대한 TA이 그것을 제안은 여기

enter image description here

(나는 또한 코드가 아래에 붙여 넣은) 현재 상태에서의 repo입니다 보석 버전 충돌 일 수 있습니다. 나는 Rails 5.1.4를 사용하고있다. (어쩌면 초보자 실수 일 수도있다. 가장 좋은 방법은 가장 좋은 방법이다.) 과정의 교사는 레일스 4를 사용하고 있습니다. TA는 코스와 동일한 보석 버전을 사용하도록 제안 했으므로 Gemfile을 코스 Gemfile과 일치하도록 업데이트하고 번들 설치를 실행하고 그걸로 레일을 얻을 수도 없습니다 실행할 서버. 다른 오류가 발생합니다. 그래서 나는 Rails 5를 사용하여이 응용 프로그램을 실행하려고합니다. 그러나 문제가 있다면 보석 버전 충돌을 해결하기위한 경험이 없습니다.

모델

class Stock < ActiveRecord::Base 

    def self.new_from_lookup(ticker_symbol) 
     looked_up_stock = StockQuote::Stock.quote(ticker_symbol) 
     new(name: looked_up_stock.name, ticker: looked_up_stock.symbol, last_price: looked_up_stock.l) 
    end 
end 

컨트롤러

class StocksController < ApplicationController 

    def search 
     @stock = Stock.new_from_lookup(params[:stock]) 
     render json: @stock 
    end 
end 

보기

0 :

다음은 관련 코드입니다

Gemfile

source 'https://rubygems.org' 

git_source(:github) do |repo_name| 
    repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") 
    "https://github.com/#{repo_name}.git" 
end 


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 
gem 'rails', '~> 5.1.4' 
gem 'devise' 
gem 'twitter-bootstrap-rails' 
gem 'jquery-rails' 
gem 'devise-bootstrap-views' 
gem 'stock_quote' 
# Use Puma as the app server 
gem 'puma', '~> 3.7' 
# Use SCSS for stylesheets 
gem 'sass-rails', '~> 5.0' 
# Use Uglifier as compressor for JavaScript assets 
gem 'uglifier', '>= 1.3.0' 
# See https://github.com/rails/execjs#readme for more supported runtimes 
# gem 'therubyracer', platforms: :ruby 

# Use CoffeeScript for .coffee assets and views 
gem 'coffee-rails', '~> 4.2' 
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks 
gem 'turbolinks', '~> 5' 
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 
gem 'jbuilder', '~> 2.5' 
# Use Redis adapter to run Action Cable in production 
# gem 'redis', '~> 3.0' 
# Use ActiveModel has_secure_password 
# gem 'bcrypt', '~> 3.1.7' 

# Use Capistrano for deployment 
# gem 'capistrano-rails', group: :development 

group :development, :test do 
    gem 'sqlite3' 
    # Call 'byebug' anywhere in the code to stop execution and get a debugger console 
    gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 
    # Adds support for Capybara system testing and selenium driver 
    gem 'capybara', '~> 2.13' 
    gem 'selenium-webdriver' 

end 

group :development do 
    # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. 
    gem 'web-console', '>= 3.3.0' 
    gem 'listen', '>= 3.0.5', '< 3.2' 
    # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 
    gem 'spring' 
    gem 'spring-watcher-listen', '~> 2.0.0' 

end 

group :production do 
    gem 'pg' 
end 

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem 
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 

은 어떤 도움에 감사드립니다!

답변

0

"주식"이라는 매개 변수가 필요합니다. 4 호선에서

@stock = Stock.new_from_lookup(params[:stock]) 

시세 기호 인 "stock"이라는 URL 매개 변수를 찾고 있습니다. 주식 PARAM을 만들고 그것을 찾아 뭔가를 줄 것이다

localhost:3000/search_stocks?stock=goog 

: 같은 것을보십시오. param이 nil 인 경우를 처리 할 수있는 코드를 추가 할 수도 있습니다.

def search 
    if params[:stock] 
     @stock = Stock.new_from_lookup(params[:stock]) 
    else 
     # you should have some directions here for what happens if there is no stock param given. 
     @stock = nil 
    end 
    render json: @stock 
end 

은 아마 더 나은 모델에 그렇게, 지금은 그것을 생각 :

def self.new_from_lookup(ticker_symbol) 
    if ticker_symbol 
     looked_up_stock = StockQuote::Stock.quote(ticker_symbol) 
    else 
     # something here for a missing stock param 
     looked_up_stock = Stock.first 
    end 
    new(name: looked_up_stock.name, ticker: looked_up_stock.symbol, last_price: looked_up_stock.l) 
end 

난이 도움이되기를 바랍니다!

+1

에 도움이 모델

def self.find_by_ticker(ticker_symbol) where(ticker: ticker_symbol).first end def self.new_from_lookup(ticker_symbol) begin looked_up_stock = StockQuote::Stock.quote(ticker_symbol) price = strip_commas(looked_up_stock.l) new(name: looked_up_stock.name, ticker: looked_up_stock.symbol, last_price: price) rescue Exception => e return nil end end def self.strip_commas(number) number.gsub(",", "") end 

이 기본적으로 내 문제에 대한 정답입니다. 큰 시간을 facepalm 순간 ... 나는 잘못된 경로에서 시작했다. 내가해야 할 일은 검색 입력이있는/my_portfolio에서 시작하는 것입니다. 그런 다음 검색을 클릭하면/search_stocks로 라우트되어 URL params를 통해 입력 값이 전달됩니다. 100 % 잘 작동합니다. https://stock-tracker-app-sb.herokuapp.com/my_portfolio (너무 당혹 스럽네요). 감사합니다. @ joaquin-roca와 바보를 조사 할 시간을 가졌습니다. 당신의 대답은 제가 잘못하고있는 것을 알아 내도록 이끌었습니다. – Sarah

+0

내 기쁨. 내가 도울 수있어서 기뻐! –

0

대부분의 시간 보석 기능이 업데이트되므로이 코드를 구현하지 않는 이유는 다음과 같습니다. 나는 최근에이 유형의 프로젝트에서 테스트 된 코드를 작성했다.

희망

+0

해결책을 찾았습니까? @ 사라 –

관련 문제