如何在rails中验证服务对象?

p1tboqfb  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(345)

我有这个服务类,我需要验证以下属性 keyurl 事实上,它们生活在不同的模式上。

  1. class MobileInstallationService
  2. class << self
  3. def connected?(id)
  4. # do something to @mi
  5. end
  6. def track_usage?(id)
  7. # do something to @mi
  8. end
  9. private
  10. def load_installation(id)
  11. @mi = Installation.find id
  12. end
  13. end
  14. end

安装可以是不同的类型,这就是为什么我有一个模型 Installation 这将跟踪它们,即所有crud操作,并且每个安装都有 properties H请记住,这会有很大的不同。

  1. class Installation
  2. belongs_to :user
  3. validates user, presence: true
  4. end

下面是安装对象的示例,其中有两个属性需要验证:

  1. => #<Installation id: 25, user_id: 8, created_at: "2021-07-22 22:35:10", updated_at: "2021-07-22 22:35:25", user_id: 16, properties: {"key"=>"123", "url"=>"www.google.com"}>

但是,不同类型的安装在使用的特定方法方面几乎没有共同之处(例如,这一种 connected? 方法,但其他方法没有)。这就是为什么我不想在那里耦合执行所有crud do validate的父控制器,例如:

  1. class InstallationController < SomeController
  2. before_action :load_installation
  3. def show
  4. end
  5. def update
  6. # could validate here but this class doesn't need to know about specific types
  7. # of installation - so I don't want to introduce coupling
  8. @installation.update(properties: params[:properties])
  9. end
  10. end
  11. private
  12. def load_installation
  13. @installation = Installation.find(id)
  14. end
  15. end

我构建的表单需要一个主安装类的示例,即。 @installation 因此,理想情况下,我需要在网上做些事情 submit 行动

  1. = form_for @installation, url: installation_path(@installation.id), method: :put do |f|
  2. %button {type: "submit"} SAVE
  3. = fields_for :settings do |s|
  4. = s.text_field :key
  5. = s.text_field :url

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题