ruby-on-rails - 在 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。
谢谢你。
解决方案
不要放置路由,而是更改 POST 方法中的代码,
metric = Metric.where(field_name: '#{value}').first_or_create
然后将值分配给度量对象。(或)
metric = Metric.where(field_name: '#{value}').first_or_initialize
然后将值分配给度量对象。这将检查指标表中的特定记录,如果找到一个.first
则将起作用,它将更新详细信息,否则.initialize
(或).create
将起作用,并将创建一个新的指标记录。
推荐阅读
- javascript - 为什么我的简单 Javascript 不能根据 Recaptcha 成功和超时来启用和禁用按钮?
- c# - C# Autofac- System.MissingMethodException:无法创建接口的实例
- java - 当 Java 字符串溢出时会发生什么?
- c# - 如何使用 Xunit 对 ActionFilterAttribute 的 OnActionExecuting() 进行单元测试
- bash - 如何将 BASH shell 变量作为 getline 中的字符串传递给 AWK?
- java - BFS算法在尝试解决15个难题时没有结束JAVA
- julia - 通用注册表未能在 Julia 中更新
- python-3.x - path.exists() 函数在 python IDE-PyCharm 中的不同目录中无法正常工作
- ios - 更改 Xcode 11 模板文件
- amazon-web-services - S3FS 无法访问