Rails 4.1.0尝试从子表更新父表时没有方法错误

我有2个rails模型,一个security和stock_quote模型,如下所示

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 "not an array\n" end end private def self.add_nonexistent_security(entry) a = StockQuote.create_security(security: entry.title.capitalize, category: "Uncategorized") end def self.save_entry(entry,security_id) unless exists? guid: entry.id contents = entry.content.split(',').map {|n| n.split(" ").last } parsed_contents = contents.map{ |x| x.scan(/[\d\.-]+/)[0] }.map(&:to_f) parsed_contents.each do |content| create!( security_id: b.id, yesterday: content[0], current: content[1], change: content[2], percentage_change: content[3], high: content[4], low: content[5], published_at: entry.updated, guid: entry.id ) end end end class Security < ActiveRecord::Base has_many :stock_quotes, dependent: :destroy end 

当我去控制台做

 c = "https://spreadsheets.google.com/feeds/list/1ncyK8uXoeLobVkdiSKQcYJr2joK_uN5QSBB3814GKaw/od6/public/values" StockQuote.update_from_feed(c) 

我明白了

 (0.1ms) SELECT COUNT(*) FROM "securities" WHERE "securities"."security" = 'Sameer africa' NoMethodError: undefined method `create_security' for # 

我现在提供了stock_quote.rb的完整数据集和模型外观我正在使用feedzija gem来获取和分析rss

子模型没有这种方法属于父模型。 只有has_many或has_one有这样的方法创建或构建。 但是,还有一些其他方法使用此模式build_create_ for belongs_to association。

所以,如果你这样做,

 b.create_security(security: "Facebook", category: "Tech") 

它会工作正常。

Create是一个类方法,但您在安全实例中使用它

 b.security.create(security: "Facebook", category: "Tech") 

在下一部分中,#create_security用作类方法,必须在StackQuote的实例上调用它