简体   繁体   English

Ruby on Rails:验证没有 model 的联系表格

[英]Ruby on Rails: Validate contact form without model

I have a simple contact form that accepts the following fields (all should be required): Name, Email, phone, and message.我有一个简单的联系表格,它接受以下字段(都应该是必需的):姓名、Email、电话和消息。

I also want to validate the email address.我还想验证 email 地址。

Users should be given a response on whether or not the form submitted successfully, or if there are errors.表单是否提交成功,或者是否有错误,应该给用户一个响应。

if so, display specific errors on the view.如果是这样,请在视图上显示特定错误。

This form is not connected to any database model.此表单未连接到任何数据库 model。 I'm not saving submissions.我不保存提交。 Only mailing.只能邮寄。

I have a POST route set to contact_form in my PagesController我在 PagesController 中将 POST 路由设置为contact_form

In my PagesController I have在我的 PagesController 我有

    def contact_form
        UserMailer.contact_form(contact_form_params).deliver
    end

In my UserMailer class I have:在我的 UserMailer class 我有:

 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

This mails successfully, but there's no validation.这邮件成功,但没有验证。 I need to only run the mail block if validation passes.如果验证通过,我只需要运行邮件块。 then return a response to the user.然后向用户返回响应。

Since I have no Model, I'm not sure how to do this.由于我没有 Model,我不知道该怎么做。 All the answers I see tell people to use validates on the ActiveRecord model.我看到的所有答案都告诉人们在 ActiveRecord model 上使用validates

With the few answers:有几个答案:

(note I've updated my params) (注意我已经更新了我的参数)

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

This sends mail when valid.这会在有效时发送邮件。 However, I'm still unsure about sending info to the user但是,我仍然不确定向用户发送信息

You can make UserMailer a model and use validations on that .您可以将 UserMailer 设为 model并对其使用验证

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

Then use it like any other model.然后像任何其他 model 一样使用它。

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

If you have multiple forms associated with UserMailer, you can make separate classes to validate each Form's inputs and then pass them along to UserMailer.如果您有多个与 UserMailer 关联的 forms,则可以创建单独的类来验证每个表单的输入,然后将它们传递给 UserMailer。 You'd likely still want validations on UserMailer regardless.无论如何,您可能仍希望在 UserMailer 上进行验证。

You can use ActiveModel::Validations on your PORO the same way AR does this.您可以像 AR 一样在 PORO 上使用ActiveModel::Validations


class MyFormObject
  include ActiveModel::Validations

  def initialize(options)
    options.each_pair{|k,v|
      self.send(:"#{k}=", v) if respond_to?(:"#{k}=")
    }
  end

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

  validates :name, presence: true
  # and so on...

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM