Reputation: 622
Hi have simple rails site with no models, its used just for serving static pages.
The site has a Pages controller, but this is only serving up one home page made of partials.
Like such in the app/views/pages/home.html.erb
<%= render 'layouts/about' %>
<%= render 'layouts/services' %>
<%= render 'layouts/rooms' %>
<%= render 'layouts/breakfast' %>
<%= render 'layouts/guestbook' %>
<%= render 'layouts/contact' %>
The home page uses some html5/javascript which autoscrolls the page. So each section is prefaced with # to allow auto scrolling to that section.
<li><a class="home" href="#home">Home</a></li>
<li><a class="services" href="#services">Tarrifs</a></li>
<li><a class="portofolio" href="#portofolio">Rooms</a></li>
<li><a class="breakfast" href="#breakfast">Breakfast</a></li>
<li><a class="contact" href="#contact" >Contact </a></li>
<li><a class="services" href="#services">Blog / Whats On.</a></li>
<li><a class="guestbook" href="#guestbook">Guest Book</a></li>
<li class="description">Take a look.</li>
This all works fine. Dev site is here
Now my question / issue is : I'd like to add a rails type ContactUS page.
Following various tutorials :
They all point to having a message model,ActionMailer, and contact controller, which works if you want to have a separate contact controller.
I'm stuck at trying to figure how I can build a contactUs form but keep it the pages controller to allow the autoscrolling to work as using a contact controller seems to change all the URL routes. I know this probably isn't the Rails way, but any help would be great.
Hope that made sense. Any ideas ?
Upvotes: 1
Views: 279
Reputation: 4375
I would do following:
Add a new model called "Form", app/models/form.rb
class Form
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :message
validates :name, presence: true
validates :email, presence: true, email: true
validates :message, presence: true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
modify your pages_controller:
def new
@form = Form.new
end
def create
@form = Form.new(params[:form])
if @form.valid?
redirect_to root_path, notice: "Thanks!")
else
render "new"
end
end
Add the form html code to your app/views/pages/home.html.erb
<%= form_for @form do |f| %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %>
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :message %>
<%= f.text_area :message %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
And that´s it, you have your build in contact form.
This code is collected from one of my gems on github: https://github.com/mattherick/contact_form
For testing you can add this gem to your gemfile and run the files generators, described in the github readme.
Upvotes: 1