Charlie Davies
Charlie Davies

Reputation: 1834

Attaching an e-mail form to a controller

I would like to change the below link into an form that posts params of the form to my controller to send an email... the current link works and sends an email...

<%= button_to 'Hello', contact_pages_path, :method => :put %>

In My controller I have:

 def contact
   Contact.contact_form.deliver
 end

My Mailer:

class Contact < ActionMailer::Base
  default from: "****"
  default to: "****"

  def contact_form
    mail(:subject => "Registered")
  end


end

and in my routes I have:

  resources :pages do
  put :contact, :on => :collection
  end

I realise that I need to create a body in the mailer - but I am not sure how to create a form to do this and pass it all on. I did think about creating a model to do this, but I thought having an entire model for just sending an email from a form would be slight over kill?

Upvotes: 0

Views: 205

Answers (3)

MrDanA
MrDanA

Reputation: 11647

You can create custom forms using form_tag and then use a text_area_tag to take in the body. As long as you give it a name, it will be sent in the params. Example (using HAML):

= form_tag contact_pages_path, :method => :put
    = text_area_tag "body"
    = submit_tag "Send"

And then in your controller you can access the text in the body with params[:body].

Look here for more information about the text_area_tag (takes in many options you may want to use) and you can also read up more on the form_tag.

This also doesn't require you to make an extra model.

Upvotes: 1

piam
piam

Reputation: 653

<%= form_tag(contact_pages_path, :method => "post") do %>
  <%= text_field_tag "article", "firstname" %> 
  <%= submit_tag("Search") %>
<% end -%>

When you submit it will go to contact_pages_path and in your controller try params[:article], so its value should be "first name".

Upvotes: 0

dku.rajkumar
dku.rajkumar

Reputation: 18588

try this

In erb file

<%= form_tag(contact_pages_path, :method => "post") do %>
  From : <%= text_field_tag "from_email", "" %> <br/>
  To : <%= text_field_tag "to_email", "" %> <br/>
  Message:<br/>
  <%= = text_area_tag "message" %>
  <%= submit_tag "send" %>
<% end %>

in action

def contact
 from_email = params[:from_email]
 to_email = params[:to_email]
 message = params[:message]

 // do operation to send the mail
end

Upvotes: 0

Related Questions