Question

I have 2 rails models, a security and stock_quote model, which are as follows

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 

In the rails console when i try doing,

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

The last query generates the following error

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

What I'm i doing wrongly because my associations are correctly defined

Was it helpful?

Solution

Instead c = b.security.create(security: "Facebook", category: "Tech") you need b.create_security(security: "Facebook", category: "Tech"). This similar to

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

Read doc for ActiveRecord::Base#belongs_to

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top