Ruby on rails Can';t访问中的道具有一个关系

Ruby on rails Can';t访问中的道具有一个关系,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两种型号: class Post < ApplicationRecord has_one :metric, dependent: :destroy end class Metric < ApplicationRecord belongs_to :post end 我是否需要声明其他任何模型才能使其工作?您所做的是 post = Post.first 1 # You don't tell us what this evaluates to, but I'm assumi

我有两种型号:

class Post < ApplicationRecord
  has_one :metric, dependent: :destroy
end

class Metric < ApplicationRecord
  belongs_to :post
end
我是否需要声明其他任何模型才能使其工作?

您所做的是

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魔力的更干净的解决方案

你正在做的是

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魔力的更干净的解决方案

您不能在
nil
类上调用create方法

替代解决方案:


Metric.create(post\u id:post.id)
您不能在
nil
类上调用create方法

替代解决方案:


Metric.create(post\u id:post.id)

尝试
post.build\u Metric
post.create\u Metric
尝试
post.build\u Metric
post.create\u Metric