首页 > 解决方案 > 在 Rails 上创建创建或更新路由的正确方法是什么

问题描述

我有以下型号:

class Post < ApplicationRecord
  has_one :metric
end

class Metric < ApplicationRecord
  belongs_to :post
end

我想通过 Post 创建一个端点来创建或更新指标。我想了解要使用的正确 HTTP 动词是什么,以及如何正确创建路由。现在我有以下路线:

resources :posts, only: [] do
  resources :metrics, only: [:create, :update]
end

但这并不是我真正想要实现的目标,因为要更新指标,我需要知道指标的 id。

谢谢你。

标签: ruby-on-railsruby

解决方案


不要放置路由,而是更改 POST 方法中的代码, metric = Metric.where(field_name: '#{value}').first_or_create然后将值分配给度量对象。(或) metric = Metric.where(field_name: '#{value}').first_or_initialize然后将值分配给度量对象。这将检查指标表中的特定记录,如果找到一个.first则将起作用,它将更新详细信息,否则.initialize(或).create将起作用,并将创建一个新的指标记录。


推荐阅读