首页 > 解决方案 > 将临时(非 DB)模型与 simple_form 相关联

问题描述

我有一个 simple_form,它并不真正适用于普通模型。如果我将对象设置为:thing它似乎可以工作。

但是,我希望它有一些验证。在其他问题中,我发现这意味着我需要一个模型……但是,我不确定该模型中需要什么。所以,我做了我的模型,但我不知道如何把它们连接起来。

class ClientEmail
  include ActiveModel::Validations

  validate :cannot_be_present

  attr_accessor :to_domain

  def cannot_be_present
    newDomClients = Client.where("email like :foo", {:foo => "%#{to_domain}%"})
    errors.add(:base, "There cannot be any emails already in the database with the target domain" ) if newDomClients.length > 0
    end
end

simple_form 是:

= simple_form_for(@client_email, url: { action: "update" }, html: {class: "search_form",  method: :put }) do |f|
  .input-row
    = f.input :newDomain, :label => "New domain name", :required => true

(ETC)

最初,它说@client_email 是零,所以我初始化它(考虑到 Rails,这似乎不太必要......):

- @client_email = ClientEmail.new

但这告诉我 ClientEmail 没有 to_key 方法,所以我显然在某处缺少一堆基础设施。

标签: ruby-on-railssimple-form

解决方案


看来我需要:

  include Virtus.model
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

我不确定 Virtus 到底是什么。没有它可能是可能的,但它是我已经拥有的图书馆......


推荐阅读