Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contact Us form in Rails 3

I simply want a contact us form with name, email and message fields in my Rails app, I don't want to save(permanently) the message I just want to send the message as an email for a email account of mine. Can you help me?

Thanks!

like image 875
rodrigoalvesvieira Avatar asked Sep 15 '10 18:09

rodrigoalvesvieira


2 Answers

In Rails3, you can create an ActiveModel model:

# /app/models/contact_us.rb
class ContactUs

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :message

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

then a mailer:

# /app/mailer/contact_us_mailer.rb
class ContactUsMailer < ActionMailer::Base

  default :to => "[email protected]"

  def send(message)
    @message = message
    mail( :subject => @message.subject, :from => @message.email ) do |format|
      format.text
    end
  end
end

and a view:

# /app/views/contact_us_mailer/sent.text.erb
Message sent by <%= @message.name %>
<%= @message.message %>

I didn't test this code exactly, but I just want to let you get the idea…

like image 190
Yannis Avatar answered Sep 20 '22 08:09

Yannis


I've written a Rails Engine https://github.com/jdutil/contact_us that you can easily drop into any Rails 3+ application. I didn't add a Name field to the form, but you could fork the repo then modify it to suit your needs. It does require the Formtastic gem since I wanted an easy way to hook into peoples existing form styles though.

To install the Engine add the contact_us gem to your Gemfile:

gem 'contact_us', '~> 0.4.0'

Run bundle and the install rake task:

$ bundle
$ bundle exec rake contact_us:install

Then just modify the generated initializer in /config/initializers/contact_us.rb to have the email you want the form submissions sent to.

like image 21
JDutil Avatar answered Sep 22 '22 08:09

JDutil