ruby-on-railsherokuactionmailersendgridmail-form

send email not working Using Sendgrid & mail_form for heroku app. I get NoMethodError in Contacts#create


Hi I just followed tutorial setting up for email contact action from https://youtu.be/QIoORYeBdhs?list=PL23ZvcdS3XPK9Y4DRU-BiJtiY5L_QhUUq

I have following:

class ContactsController < ApplicationController
    def new
        @contact = Contact.new
    end

    def create
        @contact = Contact.new(params[:contact])
        @contact.request = request
        if @contact.deliver
            flash.now[:error] = nil
        else
            flash.now[:error] = "Cannot send an email."
            render :new
        end
    end
end

class Contact < MailForm::Base
    attribute :name,      :validate => true
    attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i

    attribute :message

    def headers
        {
          :subject => "My Contact Form",
          :to => "testing@gmail.com",
          :from => %("#{name}" <#{email}>)
        }
    end
end

And I have views:

views/contacts/new.html.erb
<h1> Say Hello </h1>

<div>
    <%=form_for @contact do |f|%>
        <h3>Your are now: <%=current_user.email%> </h3>

        <%= f.label :name %><br>
        <%= f.text_area :name, required: true %>

        <%= f.label :email %><br>
        <%= f.email_field :email, required: true %>

        <%= f.label :message %><br>
        <%= f.text_area :message, as: :text %>


        <%=f.submit 'Send message', class: 'button' %>
    <%end%>
</div>

views/contacts/create.html.erb
<h1> email sent </h1>

<div>
    <h3> email Sent! </h3>
</div>

I have config/routes.rb

  resources :textbook_giveaways
  resources :textbooks
  resources :contacts, only: [:new, :create]

  devise_for :users

And when I run 'rake routes'

contacts POST   /contacts(.:format)                 contacts#create
new_contact GET    /contacts/new(.:format)          contacts#new

When I click button 'Send message', I get error:

NoMethodError in Contacts#create
undefined method `length' for nil:NilClass
Extracted source (around line #4):

    <% flash.each do |type, msg| %>
        <script type="text/javascript">
          var duration = parseInt('<%= msg.length %>');
          duration = (duration >= 100) ? 6000 : 4000;
          noty({
            theme: 'bootstrapTheme',

Can you please help with this?

Update: I fixed this problem, please look at the answer below.


Solution

  • I found where was wrong. I fixed flash[:success] = "Email sent."

    class ContactsController < ApplicationController
        def new
            @contact = Contact.new
        end
    
        def create
            @contact = Contact.new(params[:contact])
            #@contact.request = request
            if @contact.deliver
                flash[:success] = "Email sent."
            else
                flash[:alert] = "Cannot send an email."
                render :new
            end
        end
    end