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

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

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

class MobileInstallationService
      class << self
        def connected?(id)
          # do something to @mi
        end

        def track_usage?(id)
          # do something to @mi
        end

        private

        def load_installation(id)
          @mi = Installation.find id
        end
      end
    end

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

class Installation

  belongs_to :user
  validates user, presence: true

end

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

=> #<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的父控制器,例如:

class InstallationController < SomeController
  before_action :load_installation

  def show
  end

  def update
      # could validate here but this class doesn't need to know about specific types
      # of installation - so I don't want to introduce coupling
      @installation.update(properties: params[:properties])
    end
  end

  private
    def load_installation
      @installation = Installation.find(id)
    end
end

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

= form_for @installation, url: installation_path(@installation.id), method: :put do |f|

  %button {type: "submit"} SAVE
    = fields_for :settings do |s|
      = s.text_field :key
      = s.text_field :url

暂无答案!

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

相关问题