Search code examples
jqueryruby-on-rails-4mail-form

rails MailForm doesn't go through validation


I can't get the validation to work:

My Contact.rb Model:

class Contact < MailForm::Base


    attribute :name  
    attribute :e_mail    
    attribute :message

  validates_presence_of :name 
  validates_format_of :e_mail, :with =>  /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  validates_presence_of :message

  def headers
    {
      :subject => "Kontaktu forma",
      :to => "myemail@domain.lv",
      :from => %("#{name}" <#{e_mail}>)
    }
  end
end

contacts_controller.rb:

class ContactsController < ApplicationController
  respond_to :html, :js
     def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact]).deliver
  end
end

new.js :

$("#main-block").html("<%= escape_javascript(render 'contact_form') %>")

_contact_form.html.erb:

  <%= form_for :contact, :remote => true, :html => {:class => 'form-horizontal' } do |f| %>

        <%= f.label :name, class: "control-label" %>
          <%= f.text_field :name %>

        <%= f.label :e_mail, class: "control-label" %>
          <%= f.email_field :e_mail %>

        <%= f.label :message, class: "control-label" %>
          <%= f.text_area :message %>
      </br>
            <%= f.submit('Send', class: "btn btn-primary")  %>
  <% end %>

create.js:

 <%= render 'save' %>

_save.js.erb:

$("ul.errors").html("")
<% if @mail.errors.any? %>
  <% @mail.errors.full_messages.each do |message| %>
    $("ul.errors").append($("<li />").html("<%= message.html_safe %>"))
  <% end %>
<% else %>
  $("#main-block").empty()
  $("#main-block").html("Ziņa ir nosūtīta. Tuvākajā laikā sniegsim atbildi!")
<% end %>

Before I had error for not having .errors method but somehow I fixed that and now it bypasses all validations and simply Accepts the POST request of my save.js.erb

EDIT: Weirdly everything seems to be workinng just fine through console.

EDIT 2: Tried changing the form_for from :contact to @contact, now I get the undefined method `errors' for nil:NilClass method in _save.js.erb


Solution

  • I think the nilClass issue is probably because the deliver method does not return a Contact. And I don't see anywhere where you are calling the validation methods. Most AR objects call validations on valid? or save. Since you're not explicitly saving anything here, I'm not sure when the validation is expected to happen. But you could be explicit about it... like

    @contact = Contact.new(params[:contact])
    @contact.deliver if @contact.valid?
    

    This should solve the nilClass issue that you were having which was probably because now @contact is a real `Contact object. Also, you're explicitly calling the validation methods.