我有两个模型:
class Post < ApplicationRecord
has_one :metric, dependent: :destroy
end
class Metric < ApplicationRecord
belongs_to :post
end
由于某种原因,我不完全了解,因此无法通过帖子创建新指标:
> post = Post.first 1
> post.metric # => Nil
> post.metric.create # NoMethodError (undefined method `create' for nil:NilClass)
为了使这项工作有效,我是否需要声明其他任何模型?
答案 0 :(得分:0)
你在做什么
post = Post.first 1
# You don't tell us what this evaluates to, but I'm assuming a post as the #metric call works
post.metric # => Nil
# You have nil
post.metric.create
# Now you're calling the create method on nil.
您需要做的是
Metric.create(post_id: Post.first.id, etc_attribute: etc_value, ...)
编辑:7urkm3n在他的评论中也说过-build_metric和create_metric是利用Rails魔术的更干净的解决方案。
答案 1 :(得分:0)
您不能在nil
类上调用create方法。
Active Record Associations DOC
post = Post.first 1
post.build_metric # will be automatically assigned post_id to metrics but not saved
post.save
#or
post.create_metric # will be automatically assigned post_id to metrics and saved
替代解决方案:
Metric.create(post_id: post.id)