联系表格邮件程序未定义的方法错误轨道

时间:2012-08-20 18:43:41

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

我整个周末都遇到了一些严重的麻烦,试图让这个基本的联系表格正常工作。

实际上,我希望用户能够完成表单,点击发送并将消息直接发送到预定义的电子邮件地址。

我不断得到的错误是:

  NoMethodError in Messages#new

  Showing C:/Sites/jobapp_v2/app/views/messages/new.html.erb where line #1 raised:

   undefined method `[]' for nil:NilClass

  Extracted source (around line #1):

  1: <%= form_for @message, :url => contact_path do |f| %>
  2: 
  3:    <div class="field">
  4:      <%= f.label :name %>

我有以下设置:

消息控制器

class MessagesController < ApplicationController

def new
   @user = current_user
    @message = Message.new
end

def create
        @message = Message.new(params[:message])

    if  @message.valid?
        NotificationsMailer.new_message(@message).deliver
        redirect_to(root_path, :notice => "Message was successfully sent.")
    else
        flash.now.alert = "Please fill all fields."
    render :new
    end
 end
end

消息模型

 class Message < ActiveRecord::Base

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

   attr_accessor :name, :email, :subject, :body

   validates :name, :email, :subject, :body, :presence => true
   validates :email, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true

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

   def persisted?
  false
   end

  end

的routes.rb

 JobappV2::Application.routes.draw do
   devise_for :users

   resources :newsletters

   match "contact" => "messages#new", :as => "contact", :via => :get
   match "contact" => "messages#create", :as => "contact", :via => :post

   get "pages/about"

   get "pages/contact"

   get "pages/terms"

   resources :jobs

   resources :users do
   resources :jobs
   end


   root :to => 'jobs#index'


   end

NotificationsMailer.rb

 class NotificationsMailer < ActionMailer::Base

   default :from => "advertise@artisanmag.co.uk"
   default :to => "tom.pinchen@artisanmag.co.uk"

   def new_message(message)
     @message = message
     mail(:subject => "Hello")
   end
 end

查看/ notification_mailer / new_message.text.erb

 Name: <%= @message.name %>

 Email: <%= @message.email %>

 Subject: <%= @message.subject %>

 Body: <%= @message.body %>

查看/消息/ new.html.erb

  <%= form_for @message, :url => contact_path do |f| %>

<div class="field">
  <%= f.label :name %>
  <%= f.text_field :name %>
</div>

<div class="field">
  <%= f.label :email %>
  <%= f.text_field :email %>
</div>

<div class="field">
  <%= f.label :subject %>
  <%= f.text_field :subject %>
</div>

<div class="field">
  <%= f.label :body %>
  <%= f.text_area :body %>
</div>


<%= f.submit "Send" %>

   <% end %>

我真的无法解决造成这种未定义方法错误的原因,所以人们可以提供的任何帮助都会非常感激!在此先感谢:)

1 个答案:

答案 0 :(得分:1)

你搞定的方式,你不需要:url =&gt; contact_path

<%= form_for @message do |f| %>

工作得很好。