I have a card model,
class Card < ApplicationRecord
has_one :meta_sm2
after_create :add_meta
private
def add_meta
self.meta_sm2.create()
end
end
After I create a card object, I get a NoMethodError which states that create function inside add_meta does not exist becase self.meta_sm2 is nil.
class MetaSm2 < ApplicationRecord
end
Error,
NoMethodError: undefined method `create' for nil:NilClass
from /Users/li-xinyang/Desktop/XX_API/app/models/card.rb:37:in `add_meta'
Solved
The correct way of creating an associated record is by calling create_association_name, so use create_meta_sm2:
def add_meta
create_meta_sm2
end
More info: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
No comments:
Post a Comment