Mykola Gogol Mykola Gogol - 15 days ago 6
Ruby Question

Show Rails Contact Form on main page

I've created a contact form in Rails 4 with this example.
But I want to display this contact form on the main/show page of my application. How can I do this?

routes.rb.

Rails.application.routes.draw do
resources :projects
resources :contacts, only: [:new, :create]
get 'welcome/index'
root 'welcome#index'
end


contacts_controller.rb

class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
@contact.request = request
if @contact.deliver
flash.now[:error] = nil
else
flash.now[:error] = 'Cannot send message.'
render :new
end
end
end


Thanks.

Answer

And easy and clean way would be to create a partial

_contact_form.html.erb (Partials always starts with an underscore)

.container
  %h1 Contact
  = simple_form_for @contact, :html => {:class => 'form-horizontal' } do |f|
    = f.input :name, :required => true
    = f.input :email, :required => true
    = f.input :message, :as => :text, :required => false, :input_html => {:rows => 10}

    .hidden
      = f.input :nickname, :hint => 'Leave this field blank!'
    .form-actions
      = f.button :submit, 'Send message', :class=> "btn btn-primary"

Then, in your index page:

<%= render "contacts/contact_form" %>

and in your controller index action( I don't know if 'welcome/index' is on project's controller or contacts controller)

def index
 #your code
 @contact = Contact.new
end 

Finally, you seem quite new to rails, I'd like to recommend a free Ruby on Rails Tutorial