Rails如何从子模型创建父模型的新记录

时间:2014-05-08 07:57:25

标签: ruby-on-rails activerecord ruby-on-rails-4

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

class StockQuote < ActiveRecord::Base
  belongs_to :security, class_name: "Security", foreign_key: 'security_id'
end

class Security < ActiveRecord::Base
  has_many :stock_quotes, dependent: :destroy
end 

在我尝试的时候在rails控制台中,

 a = Security.create(security: "Goldman Sachs", category: "Investment Banking")
 b = a.stock_quotes.first
 c = b.security.create(security: "Facebook", category: "Tech")

最后一个查询生成以下错误

 Security Load (0.3ms)  SELECT  "securities".* FROM "securities"  WHERE "securities"."id" = ? LIMIT 1  [["id", 2]]
 NoMethodError: undefined method `create' for #<Security:0xbbd2d78>

我做错了什么,因为我的关联被正确定义

1 个答案:

答案 0 :(得分:1)

而是c = b.security.create(security: "Facebook", category: "Tech")您需要b.create_security(security: "Facebook", category: "Tech")。这类似于

 b.security = Security.new;
 b.security.save; b.security

阅读ActiveRecord::Base#belongs_to

的文档