Dan Mitchell
Dan Mitchell

Reputation: 864

Rails 4 One page App contact form

I have a single page app with a contact form at the bottom but I am getting undefined method for all of my fields

undefined method `spam' for #<Contact:0x007fe9e4471ff0>

Welcome Controller

  def index
    @contact = Contact.new
  end

  def submit
    redirect_to root_path and return if params[:spam].present?
    @contact = Contact.new(contact_params)
    if @contact.valid?
      ContactFormMailer.admin(@contact).deliver
      redirect_to root_url
      flash[:success] = "Message sent! Thank you for contacting us"
    else
      redirect_to(:action => 'index')
    end
  end

  private

  def contact_params
    params.require(:contact).permit(:spam, :first_name, :last_name, :email, :phone, :message)
  end

Form on welcome#index.html.erb

   <%= simple_form_for :contact_form, url: contact_form_path, method: :post do |f| %>
      <%= f.input :spam, as: :hidden %>
      <%= f.input :first_name %>
      <%= f.input :last_name %>
      <%= f.input :email %>
      <%= f.input :phone %>
      <%= f.input :message, as: :text %>
      <%= f.submit 'Submit', class: "button small" %>
    <% end %>

Contact Model

class Contact < ActiveRecord::Base
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :email, presence: true, :format => { :with => %r{.+@.+\..+} }
  validates :message, presence: true

end

Routes

  match '/contact' => 'welcome#index', :via => :get
  match '/contact' => 'welcome#submit', :via => :post

Upvotes: 0

Views: 342

Answers (1)

Paul Groves
Paul Groves

Reputation: 4051

Has your Contact model actually got a spam attribute?

Check by looking in your migration, or fire up the Rails console and just enter Contact and it will show you the attributes it knows about.

Upvotes: 1

Related Questions