簡體   English   中英

Ruby on Rails:驗證沒有 model 的聯系表格

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

我有一個簡單的聯系表格,它接受以下字段(都應該是必需的):姓名、Email、電話和消息。

我還想驗證 email 地址。

表單是否提交成功,或者是否有錯誤,應該給用戶一個響應。

如果是這樣,請在視圖上顯示特定錯誤。

此表單未連接到任何數據庫 model。 我不保存提交。 只能郵寄。

我在 PagesController 中將 POST 路由設置為contact_form

在我的 PagesController 我有

    def contact_form
        UserMailer.contact_form(contact_form_params).deliver
    end

在我的 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

這郵件成功,但沒有驗證。 如果驗證通過,我只需要運行郵件塊。 然后向用戶返回響應。

由於我沒有 Model,我不知道該怎么做。 我看到的所有答案都告訴人們在 ActiveRecord model 上使用validates

有幾個答案:

(注意我已經更新了我的參數)

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

這會在有效時發送郵件。 但是,我仍然不確定向用戶發送信息

您可以將 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

然后像任何其他 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

如果您有多個與 UserMailer 關聯的 forms,則可以創建單獨的類來驗證每個表單的輸入,然后將它們傳遞給 UserMailer。 無論如何,您可能仍希望在 UserMailer 上進行驗證。

您可以像 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