Search code examples
ruby-on-railscontact-formmail-form

Rails - Mail_form how to automatically set "from" field to current_user email


I followed this guide https://rubyonrailshelp.wordpress.com/2014/01/08/rails-4-simple-form-and-mail-form-to-make-contact-form/

In the contact form, the user fills out a field for their name and email along with the message.

class ContactForm < MailForm::Base

  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname,  :captcha  => true

  # Declare the e-mail headers. It accepts anything the mail method
  # in ActionMailer accepts.
  def headers
    {
      :subject => "My Contact Form",
      :to => "[email protected]",
      :from => %("#{name}" <#{email}>)
    }
  end
end

I want to automatically send from the user.email attribute and not have the user fill out a field. Is this possible?


Solution

  • Trh this:

    In your, app/views/contacts/new.html.erb make email field as hidden field and use current_user.email as value of hidden email field should work.

    Note: I am assuming you are using Devise gem