如何在后端(Rails)上验证电子邮件,并允许不在表单中填写此字段



我正在制作一个简单的单页联系表格。联系人模型有两个属性:电话和电子邮件。电子邮件应该在后端进行验证(我在我的模型中做到了)。但是用户可以在联系表单中填写电子邮件或电话并发送。不需要电子邮件字段,我不知道如何使其成为可选字段。

联系.rb

class Contact < MailForm::Base
attribute :phone
attribute :email,     :validate => /A([w.%+-]+)@([w-]+.)+([w]{2,})z/i, 
                      presence: false
def headers
  {
    :subject => "My Contact Form",
    :to => "email@admin.com",
    :from => %("#{phone}" <#{email}>)
  }
end

结束

contacts_controller.rb

class ContactsController < ApplicationController
   def new
     @contact = Contact.new
   end
   def create
     @contact = Contact.new(contact_params)
     @contact.request = request
     if @contact.deliver
       flash.now[:notice] = 'Ваша заявка принята!'
       render :new
     else
       flash.now[:notice] = 'Введите корректный email.'
       render :new
     end
   end
  private
  def contact_params
    params.require(:contact).permit(:phone, :email)
  end
end

新.html.erb

<%= simple_form_for @contact, html: {class: 'form-inline'} do |f| %>
      <div class="form-group">
          <div class="col-sm-6">
              <%= f.input_field :email, class: "form-control", placeholder: "email", required: false %>
          </div>
      </div>
      <div class="form-group">
          <div class="col-sm-6">
              <%= f.input_field :phone, class: "form-control", placeholder: "+7 (095) 123-45-67" %>
          </div>
      </div>
      <div class="form-group">
          <div class="col-sm-6">
              <%= f.button :submit, 'Submit', :class=> "btn btn-success" %>
          </div>
      </div>
      <div class="form-group">
        <div class="col-sm-12">
          <% flash.each do |key, value| %>
              <div class="alert alert-info" role="alert">
                 <div class="alert alert-<%= key %>"><%= value %></div>
              </div>
          <% end %>
        </div>
      </div>
<% end %>

我可能会这样做:

class Contact < MailForm::Base
  attribute :phone
  attribute :email,     :validate => /A([w.%+-]+)@([w-]+.)+([w]{2,})z/i, 
                      presence: false, allow_blank: true
  validate :at_least_a_contact
  def headers
    {
      :subject => "My Contact Form",
      :to => "email@admin.com",
      :from => %("#{phone}" <#{email}>)
    }
  end
  private
    def at_least_a_contact
      unless phone.present? || email.present?
        errors.add(:contact, "You need at least a contact method")
      end
    end
end

模型中的验证中使用allow_blank: true

http://guides.rubyonrails.org/active_record_validations.html#allow-blank

最新更新