整个周末我都遇到了一些严重的麻烦,试图让这个基本的联系表格正常工作。
实际上,我希望用户能够填写表格,点击发送并将消息直接发送到预定义的电子邮件地址。
我不断得到的错误是:
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
路由.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 %>
我真的无法弄清楚是什么导致了这个未定义的方法错误,所以人们可以提供的任何帮助将不胜感激!提前致谢 :)