Ruby on Rails:验证不带模型的联系表单

goo*_*oon 0 ruby-on-rails

我有一个简单的联系表单,接受以下字段(全部为必填字段):姓名、电子邮件、电话和消息。

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

应向用户提供有关表单提交是否成功或是否有错误的响应。

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

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

contact_form我在 PagesController 中设置了 POST 路由

在我的 PagesController 中我有

    def contact_form
        UserMailer.contact_form(contact_form_params).deliver
    end
Run Code Online (Sandbox Code Playgroud)

在我的 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
Run Code Online (Sandbox Code Playgroud)

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

由于我没有模型,我不知道该怎么做。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
Run Code Online (Sandbox Code Playgroud)
 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
Run Code Online (Sandbox Code Playgroud)

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

Sch*_*ern 7

您可以使 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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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