0
votes

Using rails 4.1, I am rendering a contact partial on my root => pages#home. Upon failing the create action, it renders contacts/new. And upon success will render create.

What is the best way to render the current root path with validations? I'd like to keep everything within the same view, if error or success. I have found similar answers, many on rails 3 or prior. Nothing seemed to work.

Partial View

 <%= simple_form_for @contact, :html => {:class => 'form-horizontal col-sm-12'} do |f| %>

Controller

class ContactsController < ApplicationController
     def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])
    @contact.request = request
    if @contact.deliver
      flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
    else
      flash.now[:error] = 'Cannot send message.'
      render :new
    end
  end

end
1
I've answered your question, but it's worth mentioning that simple_form provides lots of nice functionality to do this for you. - Adam Waite

1 Answers

0
votes

Calling @contact.valid? will populate @contact.errors.full_messages with any validation failures. You could then create a partial, something along the lines of:

<%- unless model.errors.full_messages.empty? %>

  <ul>

    <%- model.errors.full_messages.each do |message| ->

      <li><%= message %></li>

   <%- end %>

  </ul>

<%- end %>

and then render the partial in the root action's view:

<%= render partial: "path/to/partial", locals: { model: @contact } %>