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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.