我有一个rails应用程序从以下rss_feed
获取数据a="https://spreadsheets.google.com/feeds/list/1ncyK8uXoeLobVkdiSKQcYJr2joK_uN5QSBB3814GKaw/od6/public/values"
我使用feedjira来获取和解析来自Feed的数据。我有2个模型,security.rb和stock_quote.rb模型,如下所示:
security.rb
# == Schema Information
#
# Table name: securities
#
# id :integer not null, primary key
# security :string(255)
# category :string(255)
# created_at :datetime
# updated_at :datetime
#
class Security < ActiveRecord::Base
has_many :stock_quotes, dependent: :destroy
end
stock_quote.rb
# == Schema Information
#
# Table name: stock_quotes
#
# id :integer not null, primary key
# security_id :integer
# guid :string(255)
# created_at :datetime
# updated_at :datetime
# yesterday :decimal(8, 2)
# current :decimal(8, 2)
# price_change :string(255)
# percentage_change :string(255)
# high :decimal(8, 2)
# low :decimal(8, 2)
# guid_id :string(255)
# published_at :datetime
#
class StockQuote < ActiveRecord::Base
belongs_to :security, class_name: "Security", foreign_key: 'security_id'
def self.price_on(date)
where("date(created_at) = ?", date).sum(:high)
end
feed_url = "https://spreadsheets.google.com/feeds/list/1ncyK8uXoeLobVkdiSKQcYJr2joK_uN5QSBB3814GKaw/od6/public/values"
def self.update_from_feed(feed_url)
feed = Feedjira::Feed.fetch_and_parse(feed_url)
unless feed.is_a?(Fixnum)
add_entries(feed.entries)
else
puts feed.inspect
end
end
def self.update_from_feed_continuously(feed_url,delay_interval=2.minutes)
feed = Feedjira::Feed.fetch_and_parse(feed_url)
add_entries(feed.entries)
loop do
sleep delay_interval
feed = Feedjira::Feed.update(feed_url)
add_entries(feed.new_entries) if feed.updated?
end
end
private
def self.add_entries(entries)
entries.each do | entry |
unless exists? guid: entry.id
b = entry.content
anydate = b.scan(/\d{4}\/\d{2}\/\d{2}/)
if !anydate.empty?
anydate.each {|s| b = b.gsub(s,'0').gsub(",",".")}
else
b = b.gsub(",",".")
end
content = b.scan(/(?<=[ *])-?\d[\d.]+/).map(&:to_f)
d=Security.find_or_create_by(security: entry.title.capitalize )
d.stockquote.create!(
yesterday: content[0],
current: content[1],
change: content[2].to_s,
percentage_change: content[3].to_s,
high: content[4],
low: content[5],
published_at: entry.updated,
guid: entry.id
);
end
end
end
end
然而,当我去我的应用程序的rails控制台并执行
时 z = "https://spreadsheets.google.com/feeds/list/1ncyK8uXoeLobVkdiSKQcYJr2joK_uN5QSBB3814GKaw/od6/public/values"
StockQuote.update_from_feed(z)
我收到错误:
NoMethodError: undefined method `stockquote' for #<String:0xcaf76a0>
我也尝试过使用
d.stockquotes.create!
但是我得到了同样的错误
NoMethodError: undefined method `stockquotes' for #<Security:0xb786e7c>
答案 0 :(得分:2)
你试过这个吗?
d.stock_quotes.create!
您的关系定义has_many :stock_quotes