NoMethodError(对于#<stockquote :: stock:0x007fe59ffb1788>未定义的方法'close'>你的意思是?克隆):

时间:2018-01-16 08:40:15

标签: ruby-on-rails

我正在关注构建财务跟踪器应用程序的udemy课程。不幸的是,我遇到了这个问题,我无法以任何方式解决它。我正在使用ruby 5.1.4。这是完整的错误:

  

NoMethodError(未定义方法`close'for    你的意思是?克隆):

这是我的stocks_controller:

class StocksController < ApplicationController
  def search
    if params[:stock]
      @stock = Stock.find_by_ticker(params[:stock])
      @stock ||= Stock.new_from_lookup(params[:stock])
    end

    if @stock
      render partial: 'lookup'
    else
      render status: :not_found, nothing: true
    end
  end
end

这是stock.rb模型:

class Stock < ApplicationRecord

  def self.find_by_ticker(ticker_symbol)
    where(ticker: ticker_symbol).first
  end

  def self.new_from_lookup(ticker_symbol)
    looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
    return nil unless looked_up_stock.name
    new_stock = new(ticker: looked_up_stock.symbol, name: looked_up_stock.name)
    new_stock.last_price = new_stock.price
    new_stock
  end

  def price
    closing_price = StockQuote::Stock.quote(ticker).close
    return "#{closing_price}(Closing)" if closing_price
    opening_price = StockQuote::Stock.quote(ticker).open
    return "#{opening_price}(Opening)" if opening_price
    'Unavailable'
  end
end

我几乎遵循了整个过程,但是当我尝试使用此命令从rails控制台访问库存时问题就出现了:

StockQuote :: Stock.quote(“GOOG”)。打开

并收到此错误:

  

NoMethodError:调用私有方法`open'   

使用此命令:

StockQuote::Stock.quote("GOOG").close 

我收到此错误:

  

NoMethodError:未定义的方法`close'for           # 你的意思是?克隆

1 个答案:

答案 0 :(得分:0)

我在为股票追踪器创建应用时遇到了同样的问题,但我已通过以下步骤解决了这个问题。

尝试以下

评论此方法

# Comment
#def price
   # closing_price = StockQuote::Stock.quote(ticker).close
    #return "#{closing_price}(Closing)" if closing_price
    #opening_price = StockQuote::Stock.quote(ticker).open
    #return "#{opening_price}(Opening)" if opening_price
   # 'Unavailable'
#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

取代当前代码

#def self.new_from_lookup(ticker_symbol)
    #looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
    #return nil unless looked_up_stock.name
    #new_stock = new(ticker: looked_up_stock.symbol, name: looked_up_stock.name)
    #new_stock.last_price = new_stock.price
    #new_stock
#end

更新1

<%= render 'commom/spinner' %>下,此行添加如下

<% if @stock %>
    <strong>Symbol:</strong> <%= @stock.ticker %>
    <strong>Name:</strong> <%= @stock.name %>
    <strong>Price:</strong> <%= @stock.price %>
<% end %>

看看有什么幸福

希望能提供帮助