Search code examples
htmlruby-on-railsformsstatic-pages

RoR - Adding form over a static page


Can someone tell me how do I add a simple form in my rails app? I created a form on a separate page and it works fine, but how do I implement it on my static page?

My app/views/contact/_form.html.haml

.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"

My contacts 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[:error] = nil
        else
            flash.now[:error] = 'Cannot send message.'
            render :new
        end
    end

end

Where I want to add the form, (index.html.haml)(static page)

#callouts2
.callout_inner
    .wrapper
        .callout
            =render 'contacts/form'

My routes.rb

Rails.application.routes.draw do

  devise_for :users
  resources :posts do
    member do
      get "like", to: "posts#upvote"
      get "dislike", to: "posts#downvote"
    end
    resources :comments
  end

  authenticated :user do
    root 'posts#index', as: "authenticated_root"
  end

  resources "contacts", only: [:new, :create]

  root 'pages#index'

I also have another 'Thank you for your message' page in views/contact/create.html.haml, I need to redirect them to that page as well.

EDIT: I added a =render 'contacts/form' inside my index page but it gives me an error:

ArgumentError in Pages#index Showing C:/Sites/blogger/app/views/contacts/_form.html.haml where line #3 raised:

First argument in form cannot contain nil or be empty Trace of template inclusion: app/views/pages/index.html.haml


Solution

  • If your form is called "_form", You could do something like:

    render "form"
    

    I'm not familiar with haml, not sure what other syntax is required, but that is how you add a form into a page.