首页 > 解决方案 > Ruby on Rails:验证没有模型的联系表单

问题描述

我有一个简单的联系表格,它接受以下字段(都应该是必需的):姓名、电子邮件、电话和消息。

我还想验证电子邮件地址。

表单是否提交成功,或者是否有错误,应该给用户一个响应。

如果是这样,请在视图上显示特定错误。

此表单未连接到任何数据库模型。我不保存提交。只能邮寄。

contact_form在 PagesController 中设置了一个 POST 路由

在我的 PagesController 我有

    def contact_form
        UserMailer.contact_form(contact_form_params).deliver
    end

在我的 UserMailer 类中,我有:

 def contact_form(params)
      @formParams = params;
      @date = Time.now
         mail(
            to: "support@example.com",
            subject: 'New Contact Form Submission', 
            from: @formParams[:email],
            reply_to: @formParams[:email],
        )
    end

这邮件成功,但没有验证。如果验证通过,我只需要运行邮件块。然后向用户返回响应。

由于我没有模型,我不知道该怎么做。我看到的所有答案都告诉人们使用validates在 ActiveRecord 模型上使用。

有几个答案:

(注意我已经更新了我的参数)

class UserMailerForm
  include ActiveModel::Validations

  def initialize(options)
    options.each_pair{|k,v|
      self.send(:"#{k}=", v) if respond_to?(:"#{k}=")
    }
  end
  attr_accessor :first_name, :last_name, :email, :phone, :message

  validates :first_name, :last_name, :email, :phone, :message, presence: true
  validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } 
end
 def contact_form
    @form = UserMailerForm.new(contact_form_params)

    if @form.valid?
      UserMailer.contact_form(contact_form_params).deliver
    else
     logger.debug('invalid')
     logger.debug(@form.valid?)
    end

  end

这会在有效时发送邮件。但是,我仍然不确定向用户发送信息

标签: ruby-on-rails

解决方案


您可以使 UserMailer 成为模型在其上使用验证

class UserMailer
  include ActiveModel::Model       # make it a model
  include ActiveModel::Validations # add validations

  attr_accessor :name, :email, :phone, :message

  validates :name, :email, :phone, :message, presence: true
  validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } 

  def send_mail(subject:, to:)
    mail(
      to: to,
      subject: subject, 
      from: email,
      reply_to: email,
    )
  end
end

然后像使用任何其他模型一样使用它。

def UserMailersController < ApplicationController
  def new
    @user_mailer = UserMailer.new
  end

  def create
    @user_mailer = UserMailer.new(params)
    if @user_mailer.valid?
      @user_mailer.send_mail(
        to: "support@example.com",
        subject: 'New Contact Form Submission',
      )
    else
      # Use @user_mailer.errors to inform the user of their mistake.
      render 'new'
    end
  end
end

如果您有多个与 UserMailer 关联的表单,您可以创建单独的类来验证每个表单的输入,然后将它们传递给 UserMailer。无论如何,您可能仍希望在 UserMailer 上进行验证。


推荐阅读