Saturday, May 3, 2014

Contact form

In the last team meeting, I proposed to create a contact form to enable users a way to contact us directly if they have any question or problem that needs support. After a quick research on the Internet, I found some information about how to create forms in Rails, so I got to work...

First, I created a new Gmail account for Demigod, because I did not really have any contact email so far. Having the account, I started working on Rails by configuring the email parameters in the application.rb file:

config.action_mailer.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => "demigod.me",
  :user_name            => "new_account@gmail.com",
  :password             => "************",
  :authentication       => :plain,
  :enable_starttls_auto => true
}

config.action_mailer.default_url_options = {
  :host => "demigod.me"
}

Then, I created the message model file (message.rb), as well as the mailer model (/mailers/notifications_mailer.rb) and views. So I add the files /views/notifications_mailer/new_message.text.erb (for message layout):

Name: <%= @message.name %>

Email: <%= @message.email %>

Subject: <%= @message.subject %>

Body: <%= @message.body %>

Besides, I generated the controller file (app/controllers/contact_controller.rb), and I added the two required actions (new and create):

class ContactController < ApplicationController

  def new
    @message = Message.new
  end

  def create
    @message = Message.new(params[:message])
    
    if @message.valid?
      NotificationsMailer.new_message(@message).deliver
      redirect_to(root_path, :notice => "Your message was successfully sent")
    else
      flash.now.alert = "Error: Please fill all the fields"
      render :new
    end
  end
end

Then, I created a new Haml view file to display the form itself. I focused on the functionality rather than on the design, because I first wanted to check if it worked properly. Finally, I added the corresponding routes (GET and POST) in the routes file to make sure about the previous actions worked. I set the URL /contact to get access from the website:

match 'contact' => 'contact#new', :as => 'contact', :via => :get
match 'contact' => 'contact#create', :via => :post

I tested the new form with several examples and, fortunately, I received correctly all the emails sent through the new contact form. In the coming days, I will work on the design of the contact form, but I want to run more tests before going further. Additionally, I would like to figure out how to hide the email account and especially the password from the configuration file, because it is clear that, in terms of security, this is a huge vulnerability for our website.

No comments:

Post a Comment